在使用和更新响应式对象时,我似乎缺少 Vue Composition API 的一些东西。
参见下面的代码。我期望添加颜色时单击事件会更新模板中的
{{colors}}
输出。
<template>
<div>
<!-- {{colors}} Is not updated in the DOM on click event -->
<pre>{{ colors }}</pre>
<button @click="addColor">add color</button>
</div>
</template>
<script>
import { reactive } from 'vue';
export default {
setup() {
let colors = reactive({ green: '#ccc000' });
function addColor() {
// By cloning and creating a new merged object
colors = Object.assign({}, colors, { red: '#fff000' });
// Or by changing the object directly
colors.orange = '#322332'; // Also does not work
console.log(colors); // Logs out the correct value
}
return {
colors,
addColor,
};
},
};
</script>
我可以在控制台日志中看到颜色值正在更新,但在 DOM 中却没有。
这里是代码的代码沙箱
https://codesandbox.io/s/mystifying-roentgen-rox9k?file=/src/App.vue
您可能不应该创建新对象:
colors = Object.assign({}, colors, { red: '#fff000' });
相反,尝试操纵现有的对象:
delete colors.green;
colors.red = '#fff000';
你的颜色对象和函数应该是这样的
const colors = reactive({ green: "#ccc000" });
function addColor() {
colors.green = "rgb(23, 117, 109)";
}
不要忘记返回颜色并从设置中添加颜色
在您的模板中添加
<pre>{{ colors.green }}</pre>
<button @click="addColor">add color</button>
这应该有效
首先这样做:
colors = Object.assign({}, colors, { red: '#fff000' });
你破坏了反应性
现在这行绝对合适的代码
colors.orange = '#322332'
不起作用,因为反应性已经丧失了
解决方案是 - 删除第一次尝试
完成此任务后:
colors = Object.assign({}, colors, { red: '#fff000' });
您设置了一个对
colors
变量没有反应性的新对象,将其更改为正确的代码,您可以将其更改为:
colors = Object.assign(colors, { red: '#fff000' }, );