前言
如果想要更加的了解非父子组件传值,首先要了解父传子的思维逻辑,这样非父组件传值会更加的了解、
非父子组件传值(兄弟组件传值)
- 要了解非父组件传值首先好了解
$emit和$on,$emit(event,data)里面有两个参数第一个参数是触发的事件类型,第二个值是触发这个事件传递的参数,$on(event, callFn(data))同样$on里面也有两个参数,第一个参数是绑定的事件类型,第二个值是绑定的这个事件所对应的回调函数,里面的data值是$emit中传过来的值。
1、首先要定义一个bus(一个vue实例,用来接收事件和触发事件),代码如下、
import Vue from 'vue'
export default new Vue()
2、首先将组件引入到页面上
<template>
<div class="home">
<childrenOne></childrenOne>
<children></children>
</div>
</template>
<script>
//引入公共页面
import children from './children.vue'
import childrenOne from './childrenOne.vue'
export default {
name: 'Home',
data(){},
components: {//注册
children,
childrenOne
}
}
</script>
3、在childOne组件中将数据传入中间变量中(bus),代码如下
<template>
<div>
$emit{{namea}}
</div>
</template>
<script>
import bus from '../utli/bus'
export default {
data(){
return{
namea:"我是谁",
listone:'3332113221'
}
},
created() {
//将数值传入bus中
bus.$emit("woshishi",this.namea)
},
}
</script>
<style lang="less"></style>
4、在另一个组件中运用$on去监听bus中间变量中的值,然后再页面中显示出来
<template>
<div>
$on{{namea}}
</div>
</template>
<script>
import bus from '../utli/bus'
export default {
data(){
return{
namea:"wss"
}
},
created() {
bus.$on("woshishi",(val)=>{
this.namea = val
})
},
}
</script>
<style lang="less">
</style>