当我创建 ref
从一个空对象,然后添加对象属性,没有反应:
<template>
<p>{{hello}}</p>
<button @click="add()">Click me</button>
</template>
<script>
import {ref} from 'vue';
export default {
name: "Test",
setup(){
const myData = ref({});
return {myData}
},
methods: {
add(){
this.myData["text"] = "Hello";
console.log(this.myData);
}
},
computed: {
hello(){
return this.myData.hasOwnProperty("text")) ? this.myData["text"] : "no text";
}
}
}
</script>
点击按钮显示myData
已更改,但计算属性 hello
不更新。也试过
reactive({})
而不是 ref({})
没有成功。它在我们使用属性初始化 ref 时起作用,例如
const myData = ref({"text": "no text"});
.但是为什么空对象不起作用呢?
编辑:
终于找出问题到底是什么以及如何解决:
Vue3 的 react 性核心没有警报
Object.keys()
但只有属性的值,而空对象没有任何值。但是,如果计算属性定义为computed: {
hello(){
return Object.keys(this.myData).indexOf("text") > -1 ? this.myData["text"] : "no text";
}
调用 Object.keys(this.myData)
需要让 react 系统知道我们感兴趣的内容。这类似于设置 watch
在 Object.keys(this.myData)
而不是看this.myData
.
最佳答案
尝试更新您的 ref 对象,例如
this.myData = {"text": "Hello"}
const { ref, computed } = Vue
const app = Vue.createApp({
/*setup(){
const myData = ref({});
const hello = computed(() => myData.value.hasOwnProperty("text") ? myData.value.text : myData.value = "no text")
const add = () => {
if(Object.keys(myData.value).length === 0) {
myData.value = {'text': "Hello"};
} else {
myData.value.otherProperty = "Hello again"
}
}
return { myData, add, hello }
},*/
setup(){
const myData = ref({});
return { myData }
},
methods: {
add(){
if(Object.keys(this.myData).length === 0) {
this.myData = {"text": "Hello"}
} else {
this.myData.otherProperty = "Hello again"
}
console.log(this.myData)
},
},
computed: {
hello(){
return Object.keys(this.myData).length !== 0 ? this.myData[Object.keys(this.myData)[Object.keys(this.myData).length - 1]] : "no text"
}
}
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3.2.29/dist/vue.global.prod.js"></script>
<div id="demo">
<p>{{ hello }}</p>
<button @click="add">Click me 2 times</button>
</div>
关于javascript - 为什么 Vue3 中的空对象没有反应性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71459640/