2017-08-04 54 views
0

在嵌套对象中,我的组件中的计算属性没有很好地跟踪更改,因此计算属性未按预期触发。相反,我想在父母身上触发它。从根触发子方法(或计算属性) - vue2

什么是执行方法的正确方法,最好是从我的根计算出来的方法?

我尝试使用

this.$emit('updated');根法

this.$parent.$on('updated', this.organise);,赶上像这样,

但这返回我一个错误:

Error in event handler for "updated": "TypeError: Cannot read property 'apply' of undefined"


更新:

Vue.prototype.globalEvents = new Vue(); 

var app = new Vue({ 
    el: '#root', 
    methods: { 
     x() { 
      this.globalEvents.$emit('updated'); 
     } 
    } 
}) 

Vue.component('x', { 
    created() { 
    this.globalEvents.$on('updated', this.doStuff); 
    } 
}) 

仍然给了我同样的错误

回答

1

最简单的方法是创建全球性事件总线。你可以这样来做:

Vue.prototype.globalEvents = new Vue(); 

之后,你就可以在你的组件树从任何地方发射和监听事件:

methods: { 
myMethod() { 
    this.globalEvents.$emit(...) 
    this.globalEvents.$on(...) 
} 
} 

另外,您可以创建本地事件公交车以同样的方式,例如,创建模块调用bus.js

import Vue from 'vue'; 

const events = new Vue(); 

export default { events }; 

并使用我仅在要使用这些事件的组件中使用。

+0

我使用从cdn进行的内联脚本导入:/我还根据您提到的内容更新了我的问题。我是否需要更多步骤才能运作? – senty