Vue组件间通信方式都有哪些?
props传递数据
- 适用场景:父组件传递数据给子组件
- 子组件设置
props属性,定义接收父组件传递过来的参数 - 父组件在使用子组件标签中通过字面量来传递值
Children.vue
props:{ // 字符串形式 name:String // 接收的类型参数 // 对象形式 age:{ type:Number, // 接收的类型为数值 defaule:18, // 默认值为18 require:true // age属性必须传递 } }
Father.vue组件
<Children name="jack" age=18 />
$emit 触发自定义事件
- 适用场景:子组件传递数据给父组件
- 子组件通过
$emit触发自定义事件,$emit第二个参数为传递的数值 - 父组件绑定监听器获取到子组件传递过来的参数
Chilfen.vue
this.$emit('add', good)
Father.vue
<Children @add="cartAdd($event)" />
ref
- 父组件在使用子组件的时候设置
ref - 父组件通过设置子组件
ref来获取数据
父组件
<Children ref="foo" />
this.$refs.foo // 获取子组件实例,通过子组件实例我们就能拿到对应的数据
EventBus
- 使用场景:兄弟组件传值
- 创建一个中央事件总线
EventBus - 兄弟组件通过
$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)
$parent 或 $root
- 通过共同祖辈
$parent或者$root搭建通信侨联
兄弟组件
this.$parent.$on('add',this.add)
另一个兄弟组件
this.$parent.$emit('add')
$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>
provide 与 inject
- 在祖先组件定义
provide属性,返回传递的值 - 在后代组件通过
inject接收组件传递过来的值
祖先组件
provide(){ return { foo:'foo' } }
后代组件
inject:['foo'] // 获取到祖先组件传递过来的值
vuex
-
适用场景: 复杂关系的组件数据传递
-
Vuex作用相当于一个用来存储共享变量的容器
-
state用来存放共享变量的地方 -
getter,可以增加一个getter派生状态,(相当于store中的计算属性),用来获得共享变量的值 -
mutations用来存放修改state的方法。 -
actions也是用来存放修改state的方法,不过action是在mutations的基础上进行。常用来做一些异步操作
小结
- 父子关系的组件数据传递选择
props与$emit进行传递,也可选择ref - 兄弟关系的组件数据传递可选择
$bus,其次可以选择$parent进行传递 - 祖先与后代组件数据传递可选择
attrs与listeners或者Provide与Inject - 复杂关系的组件数据传递可以通过
vuex存放共享的变量

浙公网安备 33010602011771号