【发布时间】:2021-08-25 23:30:27
【问题描述】:
在使用和更新反应性对象时,我似乎遗漏了 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
【问题讨论】:
标签: vue.js vuejs3 vue-composition-api vue-reactivity