Mir*_*iri 26 javascript vue.js vue-component vuejs2
我正在使用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
},
}
})
Run Code Online (Sandbox Code Playgroud)
Saj*_*azy 32
// 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();
}
}
});
Run Code Online (Sandbox Code Playgroud)
Mir*_*Ali 27
对于非父子关系,这与此相同.调用一个方法,显然是任何其他组件的组件的任何方法.只需$on向$root实例添加一个函数,并调用任何其他访问$root和调用$emit函数的组件.
在第一个组件上
....
mounted() {
this.$root.$on('component1', () => {
// your code goes here
this.c1method()
}
}
并在第二个组件中调用$emit函数$root
...
c2method: function(){
this.$root.$emit('component1') //like this
},
它更像是套接字.参考这里
Eri*_*uan 11
文档解决了这种情况
https://vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication
如果组件具有相同的父组件,则可以发出父组件侦听的事件.然后使用ref属性集,您可以c1method从父级调用.
https://vuejs.org/v2/guide/components.html#Child-Component-Refs
小智 10
试试这个。
<template>
...
<component1 ref='componentOne'>
...
</template>
<script>
Vue.component('component2', {
methods: {
c2method: function(){
this.$refs.componentOne.c1method();
}
}
});
</script>
Run Code Online (Sandbox Code Playgroud)
无需黑客解决方案。
在vuejs中,我们可以创建可以全局监听的事件。
使用此功能,每当我们要调用心爱的函数时,我们都将发出此事件。
现在,我们一直都在从组件中监听此事件。每当此全局事件发生时,我们都可以执行我们要调用的方法。
它非常简单:
export const eventBus = new Vue(); // added line
new Vue({
...
...
...
render: h => h(App)
}).$mount('#app');
Run Code Online (Sandbox Code Playgroud)
eventBus.$emit('fireMethod');
Run Code Online (Sandbox Code Playgroud)
created() {
eventBus.$on('fireMethod', () => {
this.myBelovedMethod();
})
}
Run Code Online (Sandbox Code Playgroud)
不要忘记在顶部导入eventBus。
import {eventBus} from "path/to/app.js";
Run Code Online (Sandbox Code Playgroud)
就是这样,几行代码,没有hacky,所有的vuejs功能。
小智 5
如果有人在 Vue.js v3 中寻找解决方案:
https://v3-migration.vuejs.org/writing-changes/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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
38402 次 |
| 最近记录: |