我正在使用vue.js 2.5.2
我有一个对象数组,我想观看表格[*]。选择它,如果它发生更改,请调用一个函数。
这是我的尝试,但显然不正确。我尝试将数组放入for循环中,以观察每个对象的选定属性。
watch: {
for (var i = 0; i < forms.length; i++) {
forms[i].selected: function(){
console.log("change made to selection");
}
}
},
这是称为表格的对象数组[]
forms: [
{
day: '12',
month: '9',
year: '2035',
colors: 'lightblue',//default colour in case none is chosen
selected: true
},
{
day: '28',
month: '01',
year: '2017',
colors: 'lightgreen',//default colour in case none is chosen
selected: true
}
],
任何帮助将不胜感激,
谢谢
答案 0 :(得分:0)
您可以使用deep watcher,但更优雅的解决方案是为您要观看的数据创建计算属性,然后观看:
new Vue({
el: '#app',
data: () => ({
forms: [{
day: '12',
month: '9',
year: '2035',
colors: 'lightblue',
selected: true
},
{
day: '28',
month: '01',
year: '2017',
colors: 'lightgreen',
selected: true
}
],
}),
computed: {
selected() {
return this.forms.map(form => form.selected)
}
},
watch: {
selected(newValue) {
console.log("change made to selection")
}
}
})
<html>
<head>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<ul>
<li v-for="(form, i) in forms" :key="i">
<input type="checkbox" v-model="form.selected"> {{form.colors}}
</li>
</ul>
</div>
</body>
</html>