0

I am getting this warning when I try to change the value of a prop using the @click directive:

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "name"

My code is as follows:

<html>
<head>
<title>Vue test</title>
</head>
<body>
<div id="app">
    <user-name name="Flavio"></user-name>

</div>

<script src="assets/js/vue.js"></script>
<script type="text/javascript">
    Vue.component('user-name', {

      props: ['name'],
      template: '<p @click=bio1()>Hi {{ name }}</p>',

      methods: {
        bio1(){
            this.name = "Caleb";
        }
      }
    })

    new Vue({
      el: "#app"
    })
</script>

</body>
</html>

What is the cause of this warning?

Caleb Oki
  • 667
  • 2
  • 11
  • 29
  • 2
    Possible duplicate of [Vue 2 - Mutating props vue-warn](https://stackoverflow.com/questions/39868963/vue-2-mutating-props-vue-warn) – Ahmed Magdy Sep 02 '18 at 09:11

1 Answers1

2

The props in VueJS form one-way-down data binding. Meaning, you pass down the values in props to child components from parents and avoid child components to mutate these properties. Every time the parent component is updated, the updated value is refreshed in child components as well.

In your case since you need to update the value of the prop that was passed down, it’s best to define a computed property using the prop’s value:

props: ['name'],
computed: {
  localizedName: function () {
    return this.name.trim()
  }
}

Read more about one-way data flow in VueJS: https://v2.vuejs.org/v2/guide/components-props.html#One-Way-Data-Flow

tony19
  • 125,647
  • 18
  • 229
  • 307
Syed Aslam
  • 8,707
  • 5
  • 40
  • 54