1.创建一个实例Vue,作为桥梁,共享一个实例里面的方法
bridge.js
/*
* @Author: cyany_blue
* @Date: 2020-04-09 09:29:43
* @Last Modified by: cyany_blue
* @Last Modified time: 2020-04-09 09:31:37
*/
import Vue from "vue";
export default new Vue();
2.创建两个子组件
a.vue b.vue 配置路由 引入子组件
{
path: '/backEndHome',
name: 'backEndHome',
component: backEndHome,
childrens:[
{
path: '/a',
name: 'a',
component: a
},
{
path: '/b',
name: 'b',
component: b
},
]
}
import aCompoent from './a.vue'
import bCompoent from './b.vue'
export default {
name: 'backEndHome',
data() {
const item = {
date: '2016-05-02',
name: '王小虎',
address: '上海市普陀区金沙江路 1518 弄'
};
return {
tableData: Array(20).fill(item)
}
},
components:{
aCompoent,
bCompoent,
},
methods:{
}
};
<aCompoent />
<bCompoent />
3.在a.vue中引入桥梁brigde.js,使用emit方法触发函数,emit(方法名,参数)
<template>
<div class="a">
{{msg}}123456
<button @click="afun">AAAAAA</button>
</div>
</template>
<script>
import vueEvents from './../tool/bridge.js';
export default {
data(){
return {
msg:"aaaa"
}
},
created(){
vueEvents.$on('myBevent',(data)=>{
console.log(data);
this.msg="from bbb";
});
},
methods:{
afun(){
vueEvents.$emit('myAevent',this.msg);
}
}
};
</script>
4.在b组件中使用on方法监听 on(方法名,回调函数) 此处方法名同需要参数的那个方法名
<template>
<div class="b">
{{msg}}
<button @click="bFun">BBBBBB</button>
</div>
</template>
<script>
import vueEvents from './../tool/bridge.js';
export default {
data(){
return {
msg:'bbbb'
}
},
created(){
vueEvents.$on('myAevent',(data)=>{
console.log(data);
this.msg="from aaa";
});
},
methods:{
bFun(){
vueEvents.$emit('myBevent',this.msg);
}
}
};
</script>
That's all !!!