我是vuejs 2的新手。我有很多组件,在全局事件处理方面有问题,这是我的组件结构-> Image。我使用Dynamic-Component来处理我的组件。我在组件1和组件2中有表单。如果我提交表单,它将保存在allData.js文件中,并在那里显示。因此,当我研究并发现,为了与组件通信,我需要使用全局事件处理程序(EventBus)。这是我的代码(只包含脚本部分):
在我的main.js中,我包含了以下内容:
import Vue from 'vue';
import App from './App.vue';
import allData from './components/allDataTemplate.vue';
Vue.prototype.$eventHub = new Vue();
//Other codes这样,$eventHub将可以从任何组件访问,并且我不必导入到任何其他组件。
在我的App.js中,我包含了所有的表单组件:
import componentOne from './components/componentOneTemplate';
import componentTwo from './components/componentTwoTemplate';
//Other codesI m my componentOne/Two我像这样发送事件:
this.$eventHub.$emit('DataPassed', formData);现在在allData.js文件中,我需要侦听这个处理程序(可能是有问题的部分),我正在侦听该事件,并在离开时销毁它:
methods: {
whenCalled() {
console.log('fired');
}
},
created() {
this.$eventHub.$on('DataPassed', this.whenCalled);
},
beforeDestroy() {
this.$eventHub.$off('DataPassed', this.whenCalled);
}问题1:如果我销毁了事件,这里的事件不会被监听。问题2:但是如果我注释掉销毁事件,我可以监听事件,这会带来另一个问题。它触发了很多次(我访问标签的次数)。有人能帮我解决这个问题吗?
发布于 2018-08-03 01:45:55
我觉得你应该这样做
this.$eventHub.$on('DataPassed', this.whenCalled.bind(this));或者你可以这样做
this.$eventHub.$on('DataPassed', () => { this.whenCalled });我怀疑这个问题与您在$on中声明函数'whenCalled‘的作用域有关
请检查这个链接,我做了一个助手类,它是作为VueHelper注入的,优点是你可以在组件和js文件(没有组件)中抛出事件。我正在使用这段代码,我确信它可以工作。https://kopy.io/ncytP
更新的kopy.io https://kopy.io/5u63D
更新:由于kopy文件已经过期,我将在下面添加完整的代码
// Class EventEmitter
// events/index.js
import Vue from 'vue'
export class AppEventEmitter {
constructor () {
this.evt = new Vue()
}
listen (evt, callback) {
this.evt.$on(evt, callback)
}
fire (evt, data = null) {
this.evt.$emit(evt, data)
}
destroy (evt, callback) {
this.evt.$off(evt, callback)
}
}
export const AppEvent = new AppEventEmitter()
________________________________________________
// Main.js
import { AppEvent } from 'src/events'
Vue.prototype.$event = AppEvent
// Usage in vue components
this.$event.listen('ChartDataPassed', () => { this.whenCalled() })
this.$event.fire('ChartDataPassed', { value: 1, key: 'value' })
this.$event.destroy('ChartDataPassed', () => { this.whenCalled() });
// Usage in JS files
// It works even if you also throw the event in other js files by doing
AppEvent.fire('submission-process:photos-completed', { value: 1, key: 'value' })发布于 2018-08-03 00:51:35
你必须像下面这样写...
this.$eventHub.$on('DataPassed', function(payload) {
// Here you can do anything with your passed data as payload
});ES6格式,
this.$eventHub.$on('DataPassed', (payload) => {
// try something from here.
})https://stackoverflow.com/questions/51650426
复制相似问题