Vue.js - 如何从另一个组件调用方法

Vue.js - How to call method from another component

我正在使用 Vue.Js v2。提交后想在component2->c2method中调用component1->c1method重新加载数据

Vue.component('component1', {
  methods: {
    c1method: function(){
     alert('this is c1method')
    },
  }
})
Vue.component('component2', {
  methods: {
    c2method: function(){
     component('component1').c1method()//like this
    },
  }
})

文档解决了这种情况

https://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication

如果您的组件具有相同的父组件,您可以发出父组件监听的事件。然后使用 ref 属性 集,您可以从父级调用 c1method

https://vuejs.org/v2/guide/components.html#Child-Component-Refs

对于非父子关系,则与此相同。调用一个方法,显然是来自任何其他组件的组件的任何方法。只需将 $on 函数添加到 $root 实例并调用任何其他组件访问 $root 并调用 $emit 函数。

在第一个组件上

    ....
    mounted() {
        this.$root.$on('component1', () => {
            // your code goes here
            this.c1method()
        }
    }

并在第二个组件中调用 $root

中的 $emit 函数
    ...
    c2method: function(){
     this.$root.$emit('component1') //like this
    },

它更像是一个套接字。参考这里

试试这个。

<template>
 ...
 <component1 ref='componentOne'>
...
</template>
<script>
  Vue.component('component2', {
    methods: {
     c2method: function(){
       this.$refs.componentOne.c1method();
     }
   }
  });
</script>

无需骇人听闻的解决方案。
在vuejs中我们可以创建全局监听的事件。
有了这个特性,每当我们想调用我们心爱的函数时,我们只需发出这个事件。
现在,我们只是一直从组件中监听这个事件。每当这个全局事件发生时,我们就可以执行我们想要调用的方法。

很简单:

  1. 你去main.js,在创建vue实例之前,这样写:
export const eventBus = new Vue(); // added line


new Vue({
    ...
    ...
    ...
    render: h => h(App)
}).$mount('#app');


  1. 任何我们想要触发目标函数的地方,我们都不会触发它,我们只是发出这个事件:
eventBus.$emit('fireMethod');
  1. 现在在我们有目标函数的组件中,我们总是监听这个事件:
created() {
    eventBus.$on('fireMethod', () => {
            this.myBelovedMethod();
    })
}

不要忘记在顶部导入 eventBus。

import {eventBus} from "path/to/main.js";

就是这样,几行代码,没有 hacky,所有 vuejs 的力量。

// Component A
Vue.component('A', {
    created() {
        this.$root.$refs.A = this;
    },
    methods: {
        foo: function() {
            alert('this is A.foo');
        }
    }
});

// Component B
Vue.component('B', {
    methods: {
        bar: function() {
            this.$root.$refs.A.foo();
        }
    }
});

如果有人在 Vue.js v3 中寻找解决方案:

https://v3.vuejs.org/guide/migration/events-api.html#event-bus

https://github.com/developit/mitt#install

    import mitt from 'mitt'
    
    const emitter = mitt()
    
    // listen to an event
    emitter.on('foo', e => console.log('foo', e) )
    
    // listen to all events
    emitter.on('*', (type, e) => console.log(type, e) )
    
    // fire an event
    emitter.emit('foo', { a: 'b' })
    
    // clearing all events
    emitter.all.clear()