gpt4 book ai didi

javascript - 为什么 Vue.js 允许推送到 prop 数组?

转载 作者:搜寻专家 更新时间:2023-10-30 22:20:19 25 4
gpt4 key购买 nike

当我们尝试直接更改 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 是一种引用内存。当您将 ArrayObject 存储在任何变量中时,它就是一个引用变量。

内存管理 在这种情况下,引用变量将指向heap 中的内存地址,因此您可以向地址添加更多 n 个值。但是,即使是新地址,您也不能只用任何新值替换该地址。

关于javascript - 为什么 Vue.js 允许推送到 prop 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56596784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com