简体   繁体   中英

How to watch only one object in an array?

I have an array:

basicForm.schema = [
  {},
  {} // I want to watch only this
]

I tried doing this:

‘basicForm.schema[1].value’: {
  handler (schema) {
    const plan = schema.find(field => {
      return field.name === ‘plan’
    })
  },
  deep: true
},

But I got this error:

vue.js?3de6:573 [Vue warn]: Failed watching path: “basicForm.schema[1]” Watcher only accepts simple dot-delimited paths. For full control, use a function instead.

What's the correct way of doing this?

You can watch a computed property instead:

 new Vue({ el: '#app', data: { basicForm: { schema: [ {a: 1},{b: 2} // I want to watch only this ] } }, computed: { bToWatch: function() { return this.basicForm.schema[1].b } }, methods: { incB: function() { this.basicForm.schema[1].b++ } }, watch: { bToWatch: function(newVal, oldVal) { console.log(newVal) } } });
 <script src="https://unpkg.com/vue/dist/vue.js"></script> <div id="app"> <button @click="incB()">Inc</button> </div>

You should use a function as the warning message suggests. You need to do so via vm.$watch .

 new Vue({ el: '#app', data: { items: [ { name: 'bob' }, { name: 'fred' }, { name: 'sue' }, ], }, created() { this.$watch(() => this.items[1].name, this.onNameChanged); }, methods: { changeValue() { this.items[1].name = 'rose'; }, onNameChanged(name) { alert('name changed to ' + name); }, }, });
 <script src="https://unpkg.com/vue/dist/vue.js"></script> <div id="app"> <button @click="changeValue">Click me</button> </div>

You should probably check that this.items[1] exists before accessing it inside the watch function otherwise you'll get an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM