I started https://laracasts.com/series/learning-vue-step-by-step series. I stopped on the lesson Vue, Laravel, and AJAX with this error:
vue.js:2574 [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: "list" (found in component )
I have this code in main.js
Vue.component('task', {
template: '#task-template',
props: ['list'],
created() {
this.list = JSON.parse(this.list);
}
});
new Vue({
el: '.container'
})
I know that the problem is in created() when I overwrite the list prop, but I am a newbie in Vue, so I totally don't know how to fix it. Anyone have an idea how (and please explain why) to fix it?
Props down, events up. That's Vue's Pattern. The point is that if you try to mutate props passing from a parent. It won't work and it just gets overwritten repeatedly by the parent component. Child component can only emit an event to notify parent component to do sth. If you don't like these restrict, you can use VUEX(actually this pattern will suck in complex components structure, you should use VUEX!)
Vue.js considers this an anti-pattern. For example, declaring and setting some props like
So to solve this issue you have to take in a value from the props to the data or the computed property of a Vue instance, like this:
This will definitely work.
In addition to the above, for others having the following issue:
"If the props value is not required and thus not always returned, the passed data would return
undefined
(instead of empty)". Which could mess<select>
default value, I solved it by checking if the value is set inbeforeMount()
(and set it if not) as follows:JS:
Html:
do not change the props directly in components.if you need change it set a new property like this:
And change the value of listClone.
If you're using Lodash, you can clone the prop before returning it. This pattern is helpful if you modify that prop on both the parent and child.
Let's say we have prop list on component grid.
In Parent Component
In Child Component
You should not change the props's value in child component. If you really need to change it you can use
.sync
. Just like this<your-component :list.sync="list"></your-component>