当涉及到使用和更新反应对象时,我似乎遗漏了Vue组合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>我可以在控制台日志中看到colors的值正在更新,但在DOM中没有更新。
以下是代码的代码沙箱
https://codesandbox.io/s/mystifying-roentgen-rox9k?file=/src/App.vue
发布于 2021-06-09 08:38:09
您可能不应该创建新对象:
colors = Object.assign({}, colors, { red: '#fff000' });相反,请尝试操作现有对象:
delete colors.green;
colors.red = '#fff000';发布于 2021-08-04 13:47:33
您的颜色对象和函数应该如下所示
const colors = reactive({ green: "#ccc000" });
function addColor() {
colors.green = "rgb(23, 117, 109)";
}别忘了从设置中返回颜色和addColor
在您的模板中添加
<pre>{{ colors.green }}</pre>
<button @click="addColor">add color</button>这应该是可行的
https://stackoverflow.com/questions/67896043
复制相似问题