Vue组件之间的通信方式
1、通过 props 传递
适用场景:父组件传递数据给子组件
父组件在使用子组件标签中通过字面量来传递值
<Children :msg= "msgfather" age=21/>
子组件设置props属性,定义接受父组件传递过来的参数
props:{
age : Number,
msg: {
type: Number, //接受的类型为数值
default: 100, //默认值为100
require:true //value1属性必须传递
},
}
注意:msg= "msgfather"
表示向 子组件传入参数msg,注意这个参数不能使用驼峰,不然数据取不到,因为html标签属性不支持驼峰。多个单词组成的可以使用横杠连接:mytitle 或者 my-title,如果使用横杠命名的,子组件prop中接收时不能使用横杠,要使用驼峰命名。
详细的写法可以参考Vue之Props再相遇
2、$emit触发自定义事件
使用场景:子组件传递数据给父组件
子组件通过
e
m
i
t
触发自定义事件,
emit触发自定义事件,
emit触发自定义事件,emit第二个参数为传递的数值
this.$emit('add', good)
父组件绑定监听器获取到子组件传递过来的参数
<Children @add="cartAdd($event)" />
3、ref
父组件在使用子组件的时候设置ref
<Children ref="foo" />
this.$refs.foo.子组件方法名+()
this.$refs.foo.子组件属性 // 获取子组件实例,通过子组件实例我们就能拿到对应的数据
父组件通过设置子组件ref来获取数据
4、EventBus
使用场景:兄弟组件传值
创建一个中央事件总线 EventBus
兄弟组件通过
e
m
i
t
触发自定义事件,
emit触发自定义事件,
emit触发自定义事件,emit 第二个参数为为传递的数值
另一个兄弟组件通过$on监听自定义事件
Bus.js
// 创建一个中央时间总线类
class Bus {
constructor() {
this.callbacks = {}; // 存放事件的名字
}
$on(name, fn) {
this.callbacks[name] = this.callbacks[name] || [];
this.callbacks[name].push(fn);
}
$emit(name, args) {
if (this.callbacks[name]) {
this.callbacks[name].forEach((cb) => cb(args));
}
}
}
// main.js
Vue.prototype.$bus = new Bus() // 将$bus挂载到vue实例的原型上
// 另一种方式
Vue.prototype.$bus = new Vue() // Vue已经实现了Bus的功能
Children1.vue
this.$bus.$emit('foo')
Children2.vue
this.$bus.$on('foo', this.handle)
5、$parent 或 $root
通过共同祖辈
p
a
r
e
n
t
或者
parent或者
parent或者root搭建通信桥连
兄弟组件
this.$parent.on('add',this.add)
另一个兄弟组件
this.$parent.emit('add')
6、$attrs 与 $listeners
适用场景:祖先传递数据给子孙
设置批量向下传属性 $attrs 和 $listeners
包含了父级作用域中不作为prop被识别被识别(且获取)的特性绑定(class和style除外)
可以通过 v-bind=" $attrs "传入内部组件
// child:并未在props中声明foo
<p>{{$attrs.foo}}</p>
// parent
<HelloWorld foo="foo"/>
// 给Grandson隔代传值,communication/index.vue
<Child2 msg="lalala" @some-event="onSomeEvent"></Child2>
// Child2做展开
<Grandson v-bind="$attrs" v-on="$listeners"></Grandson>
// Grandson使⽤
<div @click="$emit('some-event', 'msg from grandson')">
{{msg}}
</div>
7、provide 与 inject
在祖先组件定义provide属性,返回传递的值
在后代组件通过inject接收组件传递过来的值
祖先组件
provide(){
return {
foo:'foo'
}
}
后代组件
inject:['foo'] // 获取到祖先组件传递过来的值
8、Vuex
适用场景:复杂关系的组件数据传递
Vuex
作用相当于一个用来存储共享变量的容器
- state用来存放共享变量的地方
- getter,可以增加一个getter派生状态,(相当于store中的计算属性),用来获得共享变量的值
- mutations 用来存放修改state的方法
- actions也是用来存放修改state的方法,不过action是在mutations的基础上进行。常用来做一些异步操作
- 父子关系的组件数据传递选择 props 与 $emit进行传递,也可选择ref
- 兄弟关系的组件数据传递可选择$bus,其次可以选择 $parent进行传递
- 祖先与后代组件数据传递可选择attrs与listeners或者 Provide与 Inject
- 复杂关系的组件数据传递可以通过vuex存放共享的变量