我正在尝试将 v-model
转换为数组项的属性。当我加载页面时,我在控制台中看到 "[Vue warn]: Error in render function: 'TypeError: Cannot read property 'viewFood' of undefined'
和空白页面。
这是使用 vue.js 2.x。
https://codepen.io/jzaun/pen/YxYyJN/
html
<div id="ai-config">
<div class="info">
<div class="row">
<h1>Resource Points</h1>
</div>
<div class="row">
<label>Total:</label>
<div class="value">
{{maxResourcePoints}}
</div>
</div>
<div class="row">
<label>Remaining:</label>
<div class="value">
{{maxResourcePoints - usedResourcePoints}}
</div>
</div>
</div>
<div>
<table>
<tr>
<td></td>
<td v-for="(option, idx) in options">
{{option.title}}
</td>
</tr>
<tr v-for="n in directions">
<td>Direction {{n}}</td>
<td v-for="option in options">
<input type="checkbox", v-model="selected[n][option.key]" />
</td>
</tr>
</table>
</div>
</div>
JavaScript
new Vue ({
el: '#ai-config',
data: {
maxResourcePoints: 10,
usedResourcePoints: 0,
selected: [],
directions: 8,
options: [{
title: 'Food',
key: 'viewFood',
cost: 1
}, {
title: 'Water',
key: 'viewWater',
cost: 1
}, {
title: 'Own',
key: 'viewOwn',
cost: 1
}, {
title: 'Other',
key: 'viewOther',
cost: 1
}]
},
methods: {
},
created: function () {
this.selected = [];
for(i=0; i< 8; i++) {
this.selected.push({});
}
}
});
最佳答案
有两个主要问题。
首先,Vue cannot detect当您动态地将属性添加到已添加到 Vue 数据的对象时。当你这样做时:
v-model="selected[n][option.key]"
您正在向在 create
处理程序中初始化的空对象添加一个属性。要解决这个问题,只需使用实际属性进行初始化(或使用 $set ,这似乎不是一个选项)。
this.selected.push({viewFood: false, viewOwn: false, viewWater: false, viewOther: false});
第二(以及您在问题中引用的错误的原因),当您使用范围 v-for
时,值从 1 开始。所以
v-model="selected[n][option.key]"
有一个相差一的错误,因为你可能知道,Javascript 数组是从零开始的。应该是
v-model="selected[n - 1][option.key]"
原始笔中还存在一个小的 HTML 错误
<input type="checkbox", v-model="selected[n][option.key]" />
应删除逗号的位置。
这是您的pen updated .
关于javascript - 将 v-model 与数组一起使用时,从 vue.js 收到无法读取未定义属性的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45725071/