vue组件通信
一. 你对组件化的理解: 组件树
二. vue组件通信:
1.父子通讯:父传子
在子组件中通过props接受,可以是数组[]或者是对象{}
例如:
props: {
title: {
type: String, //检查接收的数据类型
default: '请输入标题', //设置如果没有传递数据时的默认值
required:true //必填项,不传递会报错提醒
}
}
注意:不能直接修改props接收过来的值
** 如果问能否通过改变接收的props值,来更新父组件对应的值?**
props单向数据流:
父---》子
子---》不能改变父组件的值
通过添加sync属性配合$emit实现父子通讯的双向数据流:
父组件:
<header-com :title.sync="title" />
子组件:
this.$emit('update:title', 'ddddd')
- 子传父: e m i t 通 过 事 件 派 发 机 制 t h i s . emit 通过事件派发机制 this. emit通过事件派发机制this.emit(‘要派发的自定义事件名’,要传递的值)
例如:this.$emit('confirm', { name: this.name, price: this.price })
$parent: 子组件直接调用父组件
$children:父组件直接调用子组件
ref:通过ref给dom元素或组件本身添加名称来实现
例如:
<mask-dialog ref="dialog" />
JS中通过this.$refs.名子访问
例如:this.$refs.dialog
- 兄弟通讯(非父子)bus通讯:
1.创建一个空的vue并导出
import Vue from 'vue'
const Bus = new Vue();
export default Bus;
2. 在main.js中注入bus
//引入bus
import Bus from './utils/bus'
// 挂载到Vue原型上
Vue.prototype.$bus = Bus;
3. 实现派发和监听
A组件派发
this.$bus.$emit('up', this.str)
B组件监听:
created () {
this.getData();
},
methods: {
getData () {
// 监听派发的事件
this.$bus.$on('up', v => {
console.log(v)
v && (this.str = v);
})
}
}
4. 隔代通讯
$attrs $listeners
provide和inject:一般平时用不少,除非你要开发vue组件库时才会用上