object - 如何查看对象数组中的特定属性
问题描述
我正在使用 vue.js 2.5.2
我有一个对象数组,我想看 forms[*].selected 如果它改变调用一个函数。
这是我的尝试,但显然它是不正确的。我尝试将数组放入 for 循环中以观察每个对象的选定属性。
watch: {
for (var i = 0; i < forms.length; i++) {
forms[i].selected: function(){
console.log("change made to selection");
}
}
},
这是名为 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
}
],
任何帮助将不胜感激,
谢谢
解决方案
您可以使用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>
推荐阅读
- lua - 如何在排行榜中添加标题?ROBLOX LUA
- typescript - 如何在打字稿中使用代理?
- kubernetes - 如何识别 GKE 抢占节点事件
- c++ - OpenGL 和 GLM 矩阵无法正确缩放,总是按比例缩小
- php - 从 PHP 中的函数返回值时无法获得结果
- python - 在 django 设置中设置一个变量,条件是 dockerized
- c# - 选择另一个项目时,先前选择的项目的 UWP NavigationView 前景色不会更新
- unit-testing - 在 Flutter 中使用 StreamSubscription 测试 BLoC
- google-apps-script - 在自定义函数中使用 fetchAll 并行化请求会导致它崩溃
- flutter - 我想在firestore中获取图片链接