如何查看对象数组中的特定属性 [英] How to vue watch a specific property in an array of objects
问题描述
我使用的是 vue.js 2.5.2
我有一个对象数组,我想查看 forms[*].selected 并且如果它改变调用一个函数.
这是我的尝试,但显然不正确.我尝试将数组放入 for 循环中以观察所选对象的每个属性.
观看:{for (var i = 0; i
这是一个名为 forms[] 的对象数组
形式:[{天:'12',月份:'9',年份:'2035',colours: 'lightblue',//默认颜色,如果没有被选择选择:真},{天:'28',月份:'01',年份:'2017',colours: 'lightgreen',//默认颜色,如果没有被选择选择:真}],
任何帮助将不胜感激,
谢谢
你可以使用 深度观察者,但更优雅的解决方案是创建您想要观察的数据的计算属性,然后观察它:
new Vue({el: '#app',数据:() =>({形式: [{天:'12',月份:'9',年份:'2035',颜色:'浅蓝色',选择:真},{天:'28',月份:'01',年份:'2017',颜色:'浅绿色',选择:真}],}),计算:{选择(){返回 this.forms.map(form => form.selected)}},手表: {选择(新值){console.log("更改选择")}}})
<头><script src="https://unpkg.com/vue/dist/vue.js"></script>头部><身体><div id="应用程序"><ul><li v-for="(form, i) in forms" :key="i"><input type="checkbox" v-model="form.selected">{{form.colors}}
</html>
I'm using vue.js 2.5.2
I have an array of objects and I'd like to watch forms[*].selected and if it changes call a function.
This is my attempt, but obviously it is not correct. I tried putting the array into a for loop to watch each object's property selected.
watch: {
for (var i = 0; i < forms.length; i++) {
forms[i].selected: function(){
console.log("change made to selection");
}
}
},
This is the array of objects called forms[]
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
}
],
Any help would be greatly appreciated,
Thanks
You could use a deep watcher, but a more elegant solution would be to create computed property of the data you want to watch, and watch that instead:
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>
这篇关于如何查看对象数组中的特定属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!