[英]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
},
}
})
对于非父子关系,则与此相同。 从任何其他组件调用一个方法,显然是组件的任何方法。 只需将$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 },
它更像是一个套接字。 参考这里
// 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(); } } });
无需骇人听闻的解决方案。
在 vuejs 中,我们可以创建可以全局监听的事件。
有了这个特性,每当我们想要调用我们钟爱的函数时,我们就发出这个事件。
现在,我们只是一直从组件中监听这个事件。 每当这个全局事件发生时,我们就可以执行我们想要调用的方法。
这很简单:
export const eventBus = new Vue(); // added line
new Vue({
...
...
...
render: h => h(App)
}).$mount('#app');
eventBus.$emit('fireMethod');
created() {
eventBus.$on('fireMethod', () => {
this.myBelovedMethod();
})
}
不要忘记在顶部导入 eventBus。
import {eventBus} from "path/to/main.js";
就是这样,几行代码,没有hacky,所有vuejs的力量。
文档解决了这种情况
https://v2.vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication
如果您的组件具有相同的父级,则可以发出父级侦听的事件。 然后使用ref
属性集,您可以从父级调用c1method
。
https://v2.vuejs.org/v2/guide/components.html#Child-Component-Refs
试试这个。
<template>
...
<component1 ref='componentOne'>
...
</template>
<script>
Vue.component('component2', {
methods: {
c2method: function(){
this.$refs.componentOne.c1method();
}
}
});
</script>
如果有人在 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.