Vue 2 - 变异道具vue-warn [英] Vue 2 - Mutating props vue-warn
问题描述
我开始 https://laracasts.com/series/learning-vue-一步一步系列。我在 Vue,Laravel和AJAX 课程上停止了这个错误:
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 <task>)
我有这个代码 main.js
Vue.component('task', {
template: '#task-template',
props: ['list'],
created() {
this.list = JSON.parse(this.list);
}
});
new Vue({
el: '.container'
})
当我覆盖列表道具时,我知道问题出在 created(),但我是Vue的新手,所以我完全不知道如何解决它。任何人都知道如何(并请解释原因)来解决它?
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?
推荐答案
如果您想在本地改变道具,您现在应该做的是在<$中声明一个字段c $ c> data 使用 props
值作为其初始值,然后改变副本:
What you should do now, in case you want to mutate a prop locally, is to declare a field in your data
that uses the props
value as its initial value and then mutate the copy:
Vue.component('task', {
template: '#task-template',
props: ['list'],
data: function () {
return {
mutableList: JSON.parse(this.list);
}
}
});
您可以在 Vue.js官方指南
注1:请注意 你应该不为你的 prop使用相同的名称
和数据
,即:
Note 1: Please note that you should not use the same name for your prop
and data
, i.e.:
data: function () { return { list: JSON.parse(this.list) } // WRONG!!
注2:,因为我觉得有一些关于的混乱
道具和反应性,我建议你看看这个主题
Note 2: Since I feel there is some confusion regarding props
and reactivity, I suggest you to have a look on this thread
这篇关于Vue 2 - 变异道具vue-warn的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!