如何查看对象数组中的特定 属性
How to vue watch a specific property in an array of objects
我正在使用 vue.js 2.5.2
我有一个对象数组,我想查看表单[*]。已选择,如果它发生变化,则调用一个函数。
这是我的尝试,但显然是不正确的。我尝试将数组放入 for 循环中以观察每个对象的 属性 selected.
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
}
],
如有任何帮助,我们将不胜感激,
谢谢
您可以使用 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>
我正在使用 vue.js 2.5.2
我有一个对象数组,我想查看表单[*]。已选择,如果它发生变化,则调用一个函数。
这是我的尝试,但显然是不正确的。我尝试将数组放入 for 循环中以观察每个对象的 属性 selected.
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
}
],
如有任何帮助,我们将不胜感激,
谢谢
您可以使用 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>