10

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?

2 Answers 2

15

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>

Sign up to request clarification or add additional context in comments.

Comments

6

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.