[Vuejs]-Vuejs props Avoid mutating a prop directly

0πŸ‘

βœ…

v-on:click="selectedPost = post" is the culprit; selectedPost is a prop here and you cannot assign to a prop.

There are two different solutions depending on what you want:

  1. Make selectedPost a local data property instead of a prop. You can then modify selectedPost but since it is no longer a prop, you cannot accept selectedPost from the parent anymore (but you’re not really doing that anyway).
data() {
  return {
    selectedPost: null
  }
}
  1. Instead of modifying selectedPost directly, you should emit an event which the parent can handle to update its data. The convention is to emit an event named like update:selectedPost which will make it work with the .sync modifier.

Change the click handler to:

@click="$emit('update:selectedPost', post)"

Then in the parent, update as follows:

<TableMenu
  :posts="posts"
  :selectedPost="selectedPost"
  @update:selectedPost="selectedPost = $event"
></TableMenu>

Or you can use .sync to make the above a bit simpler (it does the same thing):

<TableMenu
  :posts="posts"
  :selectedPost.sync="selectedPost"
></TableMenu>

Leave a comment