如何vue观察对象数组中的特定属性

问题描述 投票:5回答:1

我正在使用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 []的对象数组

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
        }
      ],

任何帮助将不胜感激,

谢谢

object vue.js watch
1个回答
2
投票

您可以使用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>
© www.soinside.com 2019 - 2024. All rights reserved.