Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 919
alex Avatar asked May 03 '17 03:05

alex


People also ask

How do I watch nested objects in Vue?

Watching for Nested Data Changes in Vue #Every time the user clicks on the button, we ++this. count , and our watcher watches for any changes in count . It then console logs the data, so we can see the new count value. That means any time the button is clicked, the value of count is shown on the console log.

What is deep in VUE watch?

Vue provides us with the deep option in the watch property to overcome this limitation. This option will allow us to watch for changes in nested data structures. This is achieved by defining our watcher to behave as an object that should receive a handler function.

Can you watch a computed property Vue?

Yes, you can setup watcher on computed property, see the fiddle.

How do I watch data changes on Vue instance?

A Watcher in Vue. js is a special feature that allows one to watch a component and perform specified actions when the value of the component changes. It is a more generic way to observe and react to data changes in the Vue instance. Watchers are the most useful when used to perform asynchronous operations.


1 Answers

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>
like image 122
Egor Stambakio Avatar answered Oct 09 '22 22:10

Egor Stambakio