Javascript Vue.js-如何从另一个组件调用方法
我正在使用Vue.jsv2。我想在component2->c2method中调用component1->c1method,以便在提交后重新加载数据Javascript Vue.js-如何从另一个组件调用方法,javascript,vue.js,vuejs2,vue-component,Javascript,Vue.js,Vuejs2,Vue Component,我正在使用Vue.jsv2。我想在component2->c2method中调用component1->c1method,以便在提交后重新加载数据 Vue.component('component1', { methods: { c1method: function(){ alert('this is c1method') }, } }) Vue.component('component2', { methods: { c2method: funct
Vue.component('component1', {
methods: {
c1method: function(){
alert('this is c1method')
},
}
})
Vue.component('component2', {
methods: {
c2method: function(){
component('component1').c1method()//like this
},
}
})
这些文件解决了这种情况 如果组件具有相同的父级,则可以发出父级侦听的事件。然后使用
ref
属性集,可以从父级调用c1方法
对于非父子关系,则这与此相同。调用一个方法,显然是从任何其他组件调用组件的任何方法。只需将$on
函数添加到$root
实例中,并从任何其他组件调用$root
并调用$emit
函数
关于第一部分
....
mounted() {
this.$root.$on('component1', () => {
// your code goes here
this.c1method()
}
}
它的作用更像一个插座。此处引用
试试这个
<template>
...
<component1 ref='componentOne'>
...
</template>
<script>
Vue.component('component2', {
methods: {
c2method: function(){
this.$refs.componentOne.c1method();
}
}
});
</script>
...
...
Vue.component('component2'{
方法:{
方法:函数(){
这个.refs.componentOne.c1方法();
}
}
});
不需要黑客解决方案
在vuejs中,我们可以创建可以全局侦听的事件
有了这个特性,每当我们想要调用我们喜爱的函数时,我们就发出这个事件
现在,我们只需一直从组件中监听此事件。每当这个全局事件发生时,我们都可以执行我们想要调用的方法
这很简单:
转到main.js,在创建vue实例之前,请编写以下内容:
在任何我们想要激发目标函数的地方,我们都不会激发它,我们只会发出以下事件:
现在,在具有目标函数的组件中,我们始终会听到以下事件:
别忘了在顶部导入eventBus
import {eventBus} from "path/to/app.js";
就是这样,几行代码,没有黑客,所有的vuejs功能。//组件A
Vue.组件('A'{
创建(){
this.$root.$refs.A=此;
},
方法:{
foo:function(){
警报(“这是A.foo”);
}
}
});
//B部分
Vue.组件('B'{
方法:{
bar:function(){
this.$root.$refs.A.foo();
}
}
});
基本上,您可以使用$on
函数向vue实例添加事件,并命名事件及其触发的函数,您还可以使用$emit
函数并调用事件名称触发该事件。我所做的是使用$root
在Vue的根实例上创建一个事件总线,现在我可以从任何子实例触发该事件。这里有更多信息=>第一个代码段在第二个括号中缺少“)”最后一个导入路径应该是main.js。非常好的解决方案我正在学习Vue.js,这个解决方案解决了我的问题!谢谢你救了我一天!谢谢你的代码应该被标记为答案,布莱利安!精彩的解决方案!
export const eventBus = new Vue(); // added line
new Vue({
...
...
...
render: h => h(App)
}).$mount('#app');
eventBus.$emit('fireMethod');
created() {
eventBus.$on('fireMethod', () => {
this.myBelovedMethod();
})
}
import {eventBus} from "path/to/app.js";