Vue.js如何在一个页面调用另一个同级页面的方法

需要在展示页里调用顶部导航栏页里的方法,两者之间没有引用关系,看了一下vue的API发现可以用这个方法实现。

https://cn.vuejs.org/v2/api/#vm-on

可以看到需要同一个vue实例来调用两个方法。所以可以建立一个中转站。

首先在任意位置新建util.js文件。


  
  
  1. import Vue from 'vue'
  2. export default new Vue

然后在两个页面都引入它,注意引入路径。

 import Utils from '../utils.js';
  
  

然后是调用方:


  
  
  1. methods: {
  2. functionA() {
  3. Utils.$emit( 'demo', 'msg');
  4. }
  5. }

最后是被调用方:


  
  
  1. mounted(){
  2. var that = this;
  3. Utils.$on( 'demo', function (msg) {
  4. console.log(msg);
  5. that.functionB();
  6. })
  7. },
  8. methods: {
  9. functionB() {
  10. ...
  11. }
  12. }

猜你喜欢

转载自blog.csdn.net/weixin_43445771/article/details/84967282