当我们尝试直接更改 prop 值时,Vue.js 会显示警告,如下所示:
Vue.component('Games', {
template: `
<div>
<ol>
<li v-for="game in games">{{ game }}</li>
</ol>
<button @click="clear">Clear games</button>
</div>
`,
props: ['games'],
methods: {
clear: function () {
this.games = [];
}
}
});
显示的警告是:
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.
我知道为什么会发生这种情况,但令我惊讶的是 .push()
不会发生这种情况。如果我更改方法以将值添加到数组而不是重写它,则不会出现警告:
methods: {
add: function () {
this.games.push('Whatever');
}
}
为什么没有警告?直接推送到 prop 是怎么回事,而重写不是?
最佳答案
只是因为Array
是一种引用内存。当您将 Array
或 Object
存储在任何变量中时,它就是一个引用变量。
内存管理
在这种情况下,引用变量将指向heap
中的内存地址,因此您可以向地址添加更多 n 个值。但是,即使是新地址,您也不能只用任何新值替换该地址。
关于javascript - 为什么 Vue.js 允许推送到 prop 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56596784/