vue中,父子组件的传值常见,方法也很简单,兄弟组件之间的传值稍微复杂一些,用的也少,在此备忘。
【一】普通方法
1、兄弟之间传递数据需要借助于事件车,通过事件车的方式传递数据
2、创建一个Vue的实例,让各个兄弟共用同一个事件机制。
3、传递数据方,通过一个事件触发bus.on(方法名,function(接收数据的参数){用该组件的数据接收传递过来的数据}),此时函数中的this已经发生了改变,可以使用箭头函数。
实例如下:
我们可以创建一个单独的js文件event.js,内容如下
import Vue from 'vue' export default new Vue
假如父组件如下:
<template> <components-a></components-a> <components-b></components-b> </template>
子组件a如下:
<template> <div class="components-a"> <button @click="abtn">A按钮</button> </div> </template> <script> import eventVue from '../../js/event.js' export default { name: 'app', data () { return { ‘msg':"我是组件A" } }, methods:{ abtn:function(){ eventVue.$emit("myFun",this.msg) //$emit这个方法会触发一个事件 } } } </script>
子组件b如下:
<template> <div class="components-a"> <div>{{btext}}</div> </div> </template> <script> import eventVue from '../../js/event.js' export default { name: 'app', data () { return { 'btext':"我是B组件内容" } }, created:function(){ this.bbtn(); }, methods:{ bbtn:function(){ eventVue.$on("myFun",(message)=>{ //这里最好用箭头函数,不然this指向有问题 this.btext = message }) } } } </script>
这样在子组件a里面点击函数就可以改变兄弟组件b里面的值了。
【二】方法一的变种
省略了外部的js文件,直接把总线放在main.js里的vue实例中,写法如下
new Vue({ el: "#app", router, data: { eventVue: new Vue() }, template: "<App/>" compnents: {App} })
在使用的时候,不需要引入外部文件,只需要在Bus前加this.$root,即可调用。
子组件a:
methods:{ abtn: function(){ this.$root.eventVue.$emit("myFun",this.msg) //$emit这个方法会触发一个事件 } }
子组件b:
methods:{ bbtn:function(){ this.$root.eventVue.$on("myFun",(message)=>{ //这里最好用箭头函数,不然this指向有问题 this.btext = message }) } }
作者:杯雪1990
链接:https://www.jianshu.com/p/edcf7a7c3768
来源:简书