首页 > 解决方案 > Vue.js 未使用 push() 检测数据更改

问题描述

attributes我有这个方法可以在我的对象中设置数据结构。

setAttributes(data) {
  const attr = data.attributes;

  attr.forEach(attribute => {
    attribute.attributes.forEach(item => {
      if (!this.attributes[attribute.name]) {
        this.$set(this.attributes, attribute.name, {
          name: attribute.name,
          attributes: []
        });
      }

      if (!this.attributes[attribute.name].attributes[item.id]) {
        this.$set(this.attributes[attribute.name].attributes, item.id, {
          name: item.name.value,
          attributes: []
        });
      }

      this.attributes[attribute.name].attributes[item.id].attributes.push(item);
    });
  });
}

一切正常,除了最后一行this.attributes[attribute.name].attributes[item.id].attributes.push(item);Vue 没有检测到数据变化并且数组仍然是空的。

据我所知,push()应该让 Vue 检测到数据更改还是不正确?

标签: javascriptarraysvue.jsecmascript-6vuejs2

解决方案


得到它使用此代码:

setAttributes(data) {
  const attr = data.attributes;

  attr.forEach(attribute => {
    const name = attribute.name
      .toLowerCase()
      .replace(/[^a-z0-9 -]/g, '')
      .replace(/\s+/g, '_');

    if (!this.attributes[name]) {
      this.$set(this.attributes, name, {
        name: attribute.name,
        attributes: {}
      });
    }

    attribute.attributes.forEach(item => {
      if (!this.attributes[name].attributes[item.id]) {
        this.$set(this.attributes[name].attributes, item.id, {
          name: item.name.value,
          attributes: []
        });
      }

      this.attributes[name].attributes[item.id].attributes.push(item);
    });
  });
}

问题是attributes在第一个 if 语句中设置为数组而不是对象。


推荐阅读