我正在尝试在数据中初始化一个空数组,然后从服务器获取一个 JSON 并填充它。
问题是数组总是有一个额外的 Observer 对象,所以当我记录它时,我看到这个:
empty items array: [ob: Observer]
这是一段代码摘录:
data() {
return {
items: []
}
},
created() {
this.$http.get('/api/menus').then(function (response) {
console.log('items before', this.items); //THIS LOGS items before: [__ob__: Observer]
this.items = [].concat(response.body);
this.items.forEach(function (item) {
console.log('item', item);
item.$add('active', false);
item.tests.forEach(function (test) {
test.$add('active', false);
});
});
}).catch(function (err) {
console.error('err', err);
});
},
问题是当尝试向数组中的对象添加新属性时出现错误:
err TypeError: item.$add is not a function
当我调试时,我看到它发生了,因为它将观察者对象视为数组的一部分。
这正常吗?我应该检查 $add 是否存在吗?那么在 View 中渲染它时,Vue 会忽略这个对象吗?
最佳答案
根据您的代码,您希望将 items
对象中的 active
属性设置为 false
。您还想将每个项目的 tests
属性中的所有属性 active
设置为 false
。
Vue.js 是响应式(Reactive)的,可以自动检测变化,但仅限于对象本身,而不是它们的属性。对于数组,vue 将仅通过这些方法检测更改(更多关于 vue.js 中的列表呈现 https://v2.vuejs.org/v2/guide/list.html#ad ):
- 推送()
- 弹出()
- 移位()
- 取消移位()
- 拼接()
- 排序()
- 反转()
但是属性呢?您可以使用 Vue.set(object, property, value)
或 this.$set
force
vue 查看数组或对象深度的变化在任何 Vue
实例中。
因此,在您的示例中,您可以这样实现它:
this.items.forEach(function (item, key) {
console.log('item', item);
this.$set(this.items[key], 'active', false);
item.tests.forEach(function (test, testKey) {
this.$set(this.items[key].tests[testKey], 'active', false);
}, this);
}, this);
它应该可以工作。这是工作示例:http://jsbin.com/cegafiqeyi/edit?html,js,output (用到了一些ES6的特性,不要混淆)
关于javascript - 视觉 : empty array automatically populated with Observer object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42995272/