一、组件通信方式表
二、组件通信演示
1. props
-
父组件定义数据代码:
data() { return { data: 'Welcome to Your Vue.js App' } }
-
子组件定义props接收数据代码
{{ msg }}
props: { msg: { type: String, default: '' }, }
2. emit&$on
-
子组件派发事件代码
<button @click="sendDataToParent">发送
methods: { sendDataToParent() { this.$emit("send", "我是子组件"); }, }
-
父组件绑定事件代码v1
<Child @send="childSend($event)" />
methods: { childSend(value) { console.log('value :>> ', value); } }
-
父组件绑定事件代码v2
mounted() { this.on("send", (value) => { console.log("parent received value is :>> ", value); }); }
3. eventbus
-
自定义bus代码:
/* eslint-disable no-unused-vars */ 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(callback => { callback(args) }); } }} module.exports = Bus
-
子组件1发送数据代码:
<button @click="send">发送
-
子组件2接收数据代码:
export default { name: "Child2", mounted() { this.$bus.on("send", (value) => { console.log("value :>> ", value); }); }, };
-
公共父组件代码:
4. $refs
-
父组件调用子组件函数/设置数据/获取数据代码:
mounted() { // ** 注意组件挂载顺序 // 获取子组件data数据 console.log("this.refs.child1.msg); // 修改子组件data数据 this.refs.child1.console("hello"); }
-
子组件代码:
5. $parent
-
子组件1通过$parent发送数据代码:
<button @click="sendDataToChild2">发送
methods: { sendDataToChild2() { this.emit("send", "我是子组件1"); }, }
-
子组件2通过$parent接收数据代码:
mounted () { this.on('send',(value)=>{ console.log('child2 received value is :>> ', value); }) }
-
公共父组件代码:
6. $children
-
父组件调用子组件函数/设置数据/获取数据代码:
mounted () { console.log('this.children); const children = this.vnode.data.ref === "child1"){ console.log('children.msg :>> ', children.msg); children.message('hello') } }
-
子组件代码:
7.parent)
// 发送修改为
this.$root.$emit("send", "我是子组件1");
// 接收修改为
this.$root.$on('send',(value)=>{
console.log('child2 received value is :>> ', value);
})
8. provide&inject
-
父组件设置provide代码
export default { provide() { return { msg: "hello vue" }; }, components: { Child, }, };
-
子组件配置孙辈组件代码
export default { components: { Grandson, }, };
-
孙辈组件通过inject获取数据代码
export default { inject: ['msg'], };
9. $attrs属性传参
案例1(父=>子传参):
-
1. 父组件传递数据代码:
-
2. 子组件接收数据代码:
{{$attrs.value}}
案例2(父=>孙传参,子桥接):
-
1. 父组件传递数据代码:
-
2. 子组件桥接属性代码:
-
3. 孙辈组件通过props属性接收数据代码:
{{ value }}props: { value: { type: String, default: "", }, },
10. $listeners事件传参
案例1(子=>父传参)
-
1. 子组件派发事件代码:
<button @click="send">发送
send() { this.$listeners.event('hello vue') }
-
2. 父组件绑定事件接收数据代码:
<Child @event="message" />
message(value) { console.log('value :>> ', value); }
案例2(孙=>父传参,子桥接)
-
1. 孙辈组件派发事件代码:
<button @click="send">发送
this.$emit("event", "hello vue");
-
2. 子组件桥接事件代码:
-
3. 父组件绑定事件接收数据代码:
<Child @event="message" />
message(value) { console.log('value :>> ', value); }