跳到主内容

Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders.

· 2分钟阅读

问题

组件封装,通过 props 传递过来的参数,在 created 生命周期进行赋值的时候报错了。代码如下

Vue.component("todo", {
template: "#todo-template",
props: ["list"],
created() {
this.list = JSON.parse(this.list);
},
});
new Vue({
el: ".container",
});

运行后控制台报了如下错误

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 )

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.

这段话翻译成中文如下

避免直接改变 props,因为每当父组件重新呈现时,该值将被覆盖。相反,使用基于 props 值的 data 或 computed 属性。props 发生了变化:"list"(在组件中找到)

原因

其实就是想要把 props 当作组件内部的属性来使用,那么完全没必要重新赋值,只需要直接拿来用就可以。

解决

解决办法很简单,直接把 this.list = JSON.parse(this.list); 这段代码去掉即可。

Vue.component("todo", {
template: "#todo-template",
props: ["list"],
created() {
this.list = JSON.parse(this.list);
},
});
new Vue({
el: ".container",
});