vue兄弟组件之间传递值汇总
vue中父传子和子传父大家肯定都滚瓜烂熟,就不说了,主要总结一下非父子之间的传递:
1:通过公共的bus
创建一个公共的bus,然后导出一个bus
bus.js
import Vue from 'vue';
export const bus = new Vue();
然后A B两个组件同时引入bus.js
import { bus } from '@/components/bus.js';
A组件$emit事件及要传的值
getBrother(){
bus.$emit('testEvent','我是要传的值')
}
B组件接收
bus.$on('testEvent',val => {
console.log(val);
this.val = val;
})
当然了也可以直接引入vue-bus
$ yarn add vue-bus
$ npm install vue-bus --save
2:通过vue2.4中$attrs和$listeners
inheritAttrs:(如下图)
true: 在文档中显示自定义属性
false:在文档中不显示自定义属性,不影响$attrs使用
从上往下传递使用$attrs,从下往上传递使用$listeners,最主要的是子组件里边的这一句<Son v-bind="$attrs" v-on="$listeners" />
父组件
<template>
<div id="app">
<HelloWorld name="hello" v-on:mj="mj" />
<Brother :name='name' v-on:myEvent="myListeners" />
</div>
</template>
methods: {
myListeners(data){
console.log(data);
}
}
子组件
<template>
<div class="brother">
<Son v-bind="$attrs" v-on="$listeners" />
</div>
</template>
孙组件
<template>
<div class="son">
{{$attrs.name}}
<button @click="chuanVal">123</button>
</div>
</template>
methods: {
chuanVal(){
this.$emit('myEvent','11111111111')
}
}
3:通过props一级一级的传,父传子 –> 子传孙 ,这种也是能实现,但是也不推荐的,层级少了可以,多了就会很难看也很难理解,就不细说了。
4:通过vuex来传递也可以实现功能,但是如果项目没有很大,使用vuex有点大材小用,这里也不细说了,大家可以去看官方文档。
补充:
5:provide(生产者)和inject(注入)
父组件来生产(provide )数据,子组件通过注入( inject )来消费数据,感觉跟react里边新版的React.createContext很像,一个生产者一个消费者,来跨组件传递数据。
父组件:
provide(){
return{
showName:function(){
console.log("父组件数据!!!!!!!!!!!!!!!!");
}
}
}
子组件:
inject: ['showName'],
created () {
console.log(this.showName());
}
欢迎关注小程序,感谢您的支持!