首页 > 解决方案 > 如何查看对象数组中的特定属性

问题描述

我正在使用 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
        }
      ],

任何帮助将不胜感激,

谢谢

标签: objectvue.jswatch

解决方案


您可以使用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>


推荐阅读