Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid mutating a prop directly since the value will be overwritten

I have very common problem with upgrading to Vue 2.0

I am getting warning:

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: "username" (found in the component )

I read the documentation many times but I still can't understand how to fix it.

username and password are declared in the main Vue app.

Here is my code:

var GuestMenu = Vue.extend({    props : ['username', 'password'],       template: `         <div id="auth">             <form class="form-inline pull-right">                 <div class="form-group">                     <label class="sr-only" for="UserName">User name</label>                   <input type="username" v-model="username" class="form-control" id="UserName" placeholder="username">                 </div>                 <div class="form-group">                   <label class="sr-only" for="Password">Password</label>                   <input type="password" v-model="password" class="form-control" id="Password" placeholder="Password">                 </div>             </form>         </div>`,     }); 

 

App = new Vue ({     el: '#app',   data:      {       topMenuView: "guestmenu",       contentView: "guestcontent",       username: "",       password: "",      } }) 

I tried v-bind but it does not seem to work, and I can't understand why. It should bind the value to parent (the main Vue app)

like image 502
Dmitry Bubnenkov Avatar asked Nov 13 '16 14:11

Dmitry Bubnenkov


People also ask

How do I fix avoid mutating a prop directly in Vue?

Here is the error message in full: Error message: 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.

How do I stop mutating prop?

The answer is simple, you should break the direct prop mutation by assigning the value to some local component variables(could be data property, computed with getters, setters, or watchers). Here's a simple solution using the watcher. It's what I use to create any data input components and it works just fine.

Is it okay to mutate props?

Short answer is: NO. Long answer is: It will not work.


Video Answer


1 Answers

From Vue 2.3.0 on you can use the .sync modifier:

Sample from https://vuejs.org/v2/guide/components-custom-events.html#sync-Modifier:

<text-document :title.sync="title"></text-document> 

and in your controller...

this.$emit('update:title', newTitle) 
like image 142
Gerfried Avatar answered Oct 06 '22 19:10

Gerfried