2017-08-04 73 views
0

我的父代数据中有一个嵌套对象,它看起来像这样。从父代中观察嵌套对象数据

obj: { 
    1: { 
    'a': [ [], [], [] ] 
    'b': [ [] ] 
    }, 
    2: { 
    'x': [ [], [] ] 
    } 
} 

虽然初始化,在我父数据,我初始化这个obj{}。当我尝试在我的子组件中使用观察器时,它仅监视1,2级密钥级别,而不是密钥级别发生更改时。但是,即使内层发生变化,我也希望它能够执行。

// in my component 
computed: { 
    watchForms() { 
     alert("X"); 
    } 
}, 

然后,我试图用发射/从根元素告诉给儿童在新元素被添加/移除的对象 - 发射事件并捕获它的组分上。

// So I set a global variable, 
Vue.prototype.globalEvents = new Vue(); 

// In my root element, initialised the obj 
data: { 
    obj: {} 
} 

// In my root element methods, when changes happen on my obj 
methods: { 
    changeHappened() { 
    this.globalEvents.$emit('updated'); 
    } 
} 

// And in my component, I tried to catch it and run the method, 
created: function() { 
    this.globalEvents.$on('updated', this.watchForms); 
}, 

[Vue warn]: Error in event handler for "updated": "TypeError: Cannot read property 'apply' of undefined" (found in)

我收到此错误,但是我不叫任何.apply():/我在做什么错?

+0

这似乎'this.watchForms'是未定义'()创建'作为参数传递给在'$(...)' – marekful

+0

是什么做的正确方法吗?每次在obj中发生什么变化都不应该触发它吗? – senty

回答

0

此前我已经回答了你的其他question此问题似乎是相关的,所以我只是要通过deep: true修改我用出了相同的片段,你就能够观看嵌套属性:

const app = new Vue({ 
 
    el: '#app', 
 
    data: { 
 
    types: {}, 
 
    history: [] 
 
    }, 
 
    watch: { 
 
    types: { 
 
     handler(newVal) { 
 
     this.history.push(JSON.stringify(newVal)); 
 
     }, 
 
     deep: true 
 
    } 
 
    }, 
 
    methods: { 
 
    pushValue(key, value) { 
 
     if (this.types.hasOwnProperty(key)) { 
 
     if (this.types[key].hasOwnProperty(value)) { 
 
      const orgValue = this.types[key][value]; 
 
      orgValue.push([]); 
 
      this.$set(this.types[key], value, orgValue); 
 
     } else { 
 
      this.$set(this.types[key], value, [[]]); 
 
     } 
 
     } else { 
 
     this.$set(this.types, key, { 
 
      [value]: [ [] ] 
 
     }); 
 
     } 
 
    } 
 
    } 
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script> 
 
<div id="app"> 
 
    <div> 
 
    <p>pushValue(key, value)</p> 
 
    <button v-on:click="pushValue(1, 'a')">(1, 'a')</button> 
 
    <button v-on:click="pushValue(1, 'b')">(1, 'b')</button> 
 
    <button v-on:click="pushValue(1, 'c')">(1, 'c')</button> 
 
    <button v-on:click="pushValue(2, 'a')">(2, 'a')</button> 
 
    <button v-on:click="pushValue(2, 'b')">(2, 'b')</button> 
 
    <button v-on:click="pushValue(2, 'c')">(2, 'c')</button> 
 
    </div> 
 
    <div>types:</div> 
 
    <div>{{ types }}</div> 
 
    <div>modified:</div> 
 
    <div v-for="item in history">{{ item }}</div> 
 
</div>