【问题标题】:Watching nested object data from parent观察来自父对象的嵌套对象数据
【发布时间】:2018-01-12 23:34:53
【问题描述】:

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

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

在初始化时,在我父母的数据中,我将这个 obj 初始化为 {}。当我尝试在我的子组件中使用观察器时,它只观察 1、2 键级别,而不是在字母键级别发生更改时。但是,即使内部级别发生变化,我也希望它能够执行。

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

然后,当新元素添加/删除到对象时,我尝试使用 emit/on 从根元素告诉子元素 - 发出事件并在组件上捕获它。

// 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 警告]:“更新”的事件处理程序出错:“TypeError:无法读取未定义的属性 'apply'”(在 中找到)

我收到此错误,但我没有打电话给任何.apply() :/ 我做错了什么?

【问题讨论】:

  • 似乎this.watchFormscreated() 中未定义为$on( ... ) 的参数
  • 正确的做法是什么?不是每次 obj 发生一些变化都会触发它吗?

标签: javascript vuejs2 vue-component


【解决方案1】:

之前我已经回答了你的另一个question,这个问题似乎是相关的,所以我将修改我使用deep: true 说明的同一个sn-p,你将能够看到嵌套属性:

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>

【讨论】:

    猜你喜欢
    • 2022-11-25
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 2015-07-19
    相关资源
    最近更新 更多