How to watch only one object in an array?

I have an array:

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

I tried to do 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]: View path error: "basicForm.schema [1]" The observer only accepts simple paths separated by periods. For full control, use the function.

What is the right way to do this?

+6
source share
2 answers

Instead watchyou can computed property:

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>
Run codeHide result
+5
source

You must use the function as a warning message. You need to do this through 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>
Run codeHide result

, , this.items[1] , , .

+3

Source: https://habr.com/ru/post/1016946/


All Articles