vue兄弟组件传值(vue兄弟组件通讯,vue同级组件传值通讯,vue兄弟组件通讯传值常用的两种方式,超详细)

您所在的位置:网站首页 vue的传值方式 vue兄弟组件传值(vue兄弟组件通讯,vue同级组件传值通讯,vue兄弟组件通讯传值常用的两种方式,超详细)

vue兄弟组件传值(vue兄弟组件通讯,vue同级组件传值通讯,vue兄弟组件通讯传值常用的两种方式,超详细)

2023-01-04 23:56| 来源: 网络整理| 查看: 265

tips: 兄弟组件,就是同级别的组件⭐

第一种: EventBus方法 首先在main.js文件中定义一个新的bus对象,然后挂载在原型链上,生成一个全新的Vue实例,具体步骤如下:

1、首先在main.js中生成一个全新的vue实例,如下:

//写在main.js中 Vue.prototype.$bus = new Vue()

2、在组件brother.vue 中,声明并监听事件 brotherEvent;

//brother.vue //在同级别组件中声明监听事件 created(){     this.$bus.$on('brotherEvent', res=>{         console.log(res) // res就是sister.vue里choseEvent方法传递的值data     }) }

3、在组件 sister.vue(和brother.vue 同级)中,触发 brotherEvent事件;

//sister.vue //在方法中调用事件 methods:{     choseEvent(){         this.$bus.$emit('brotherEvent',this.data)     } }

通讯成功●'◡'●

第二种:中间件方法 原理就是通过父组件作为中间件来通讯,结合子传父,父再传子,实现同级别间的兄弟组件传值,具体步骤如下:

1、首先在父组件引入两个子组件,并且给子组件添加自定义方法,如下:

//father.vue //组件引入 import brother from "./components/brother.vue"; import sister from "./components/sister.vue"; //组件注册 components: { brother, sister, }, //组件使用 //在子组件上添加自定义方法 @defineBrother="choseBrother" //在子组件上添加自定义方法 @defineSister="choseSister"

2、在子组件使用$emit调用子组件的自定义方法,并且传值;

//brother.vue组件 兄弟按钮 data() { return { brotherMsg: [1, 2, 3, 4], }; }, methods: { choseBrotherBtn() { this.$emit("defineBrother", this.brotherMsg); }, }, //sister.vue组件 姐妹按钮 data() { return { sisterMsg: { name: "xxx" }, }; }, methods: { choseSisterBtn() { this.$emit("defineSister", this.sisterMsg); }, },

3、父组件通过自定义方法,接收来自子组件传递的数据;

//father.vue接收数据 data() { return { data: "", msg: "", }; }, methods: { choseBrother(value) { console.log(value);//这里的value就是兄弟组件传过来的数组数据brotherMsg this.data = value;//赋值给父级组件data }, choseSister(value) { console.log(value);//这里的value就是姐妹组件传过来的数据对象sisterMsg this.msg = value;//赋值给父级组件msg }, },

4、父组件接收到数据以后,再通过父传子,传递对应数据;

//father.vue //父传子:sendFather="msg"; //把sister.vue中的数据sisterMsg 传给brother; //父传子 :sendSister="data"; //把brother.vue中的数据brotherMsg 传给sister;

5、最后使用props接收数据;

//兄弟组件 接收来自 姐妹组件 的 对象数据sisterMsg props:["sendBrother"], {{sendBrother}} //姐妹组件 接收来自 兄弟组件 的 数组数据brotherMsg props:["sendSister"], {{sendSister}}

兄弟组件(同级组件)传值通讯成功(●'◡'●)



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3