vue非父子关系的组件,实现相互调用
1. 使用$emit和 $on
vm.$ emit( event, arg ) //触发当前实例上的事件
vm.$on( event, fn );//监听event事件后运行 fn;
1.1 首先同一个vue实例来调用两个方法,可以建立中转站
建立 util.js 中转站文件(任意位置都可以,我是在 src/js/util.js)
import Vue from 'vue'
export default new Vue
1.2 分别在两个页面引入该文件(注意路径)
import Utils from '@/shift/util.js';
1.3 调用方代码
methods: {
oneFunction() {
Utils.$emit('event','传的值,可以是任意类型'); // 传一个值
Utils.$emit('eventTwo',[a, b, c, d, e, f]);
}
}
1.4 被调用方代码
mounted(){
let that = this;
// 传一个值
Utils.$on('event', (value) => {
console.log(value);
that.handleChange(); //这里就是调用你的方法
})
// 传多个值
ePie.$on('eventTwo', (...msg) => {
this.aa = val[0][0];
this.bb = val[0][1];
this.cc = val[0][2];
this.dd = val[0][3];
this.ee = val[0][4];
this.ff = val[0][5];
})
},
methods: {
handleChange() {
...
}
}
2. 使用引入方法
1.1 引入需要调用方法页面
import LayoutIndex from '@/components/Model/index.vue'
1.1 使用引入页面的别名,获取methods或者created的方法
LayoutIndex .methods.handleChange()