vue2 修改属性时报错

逛国外论坛时,遇到些有趣的问题,值得记录。
有位老哥想转义下获取的数据,但是程序报警告,之前没有遇到过,so:
代码如下:

Vue.component('task', {
    template: '#task-template',
    props: ['list'],
    created() {
        this.list = JSON.parse(this.list);
    }
});
new Vue({
    el: '.container'
})
报错如下:
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>)
正确的解释:

在本地修改一个prop,在vue2中被认为是一种反模式。
应该这么做:当你想在本地修改一个prop时,应该在data里先声明一个字段,这个字段用来初始化和修改副本。

Vue.component('task', {
    template: '#task-template',
    props: ['list'],
    data: function () {
        return {
            mutableList: JSON.parse(this.list);
        }
    }
});
 
尤大大在vue的issue里也有解释:
行内属性类似于不可变值,因为每次父组件重新渲染时,可变的子属性都会被重置到行内。依赖可变的行内属性是不可行的。
所以,如果你想用行内属性作为初始化值,那就在data里声明一个字段用来赋值。

原文地址:https://www.cnblogs.com/easonw/p/10595605.html