Vuejs2: how to judge props update when using object as a prop?

Suppose I have an array feedsArray, the example value may look like this:

this.feedsArray = [
  {
    id: 1,
    type: 'Comment',
    value: 'How are you today ?'
  },
  {
    id: 2,
    type: 'Meet',
    name: 'Daily sync up'
  }
]

Suppose I have registered two components: Comment and Meet, Each component has a prop setting as the following:

props: {
  feed: Object
}

and the main component has the following definition:

<component v-for="feed in feedsArray" :feed="feed" :key="feed.id" :is="feed.type"></component>

As you can see, it uses is property to select different component. My question is, how to detect feed object change in the child component ? Like when I set

this.feedsArray[0] = {
  id: 1,
  type: 'Comment',
  value: 'I am not ok'
}

How can the Comment component detect the changes ? I tried to add a watcher definition in the child component like the following:

watch: {
  feed: {
    handler (val) {
      console.log('this feed is changed')
    },
    deep: true
  }
},

But it doesn't work here. Anyone know how to solve this ?

1 answer

  • answered 2018-07-11 10:43 IVO GELOV

    Do not assign directly to an array using index - use splice() instead, otherwise JavaScript can not detect that you have changed the array.

    If you want to change only the value of an already existing key of an object - then simply update it e.g. this.feeds[0].value = 'I am not okay any more';

    This works for existing keys only - otherwise you have to use this.$set(this.feeds[0], 'value', 'I am not okay any more');