javascript - 为什么 Vue3 中的空对象没有反应性?

标签 javascript vue.js vuejs3 vue-reactivity

当我创建 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 系统知道我们感兴趣的内容。这类似于设置 watchObject.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/

相关文章:

datatable - PrimeVue 编辑行

javascript - 为 "scripts"使用单独的文件

javascript - 如何在uib-datepicker中设置maxdate和mindate

vue.js - 如何处理element-ui VueJS的Dialog组件中的打开事件?

checkbox - Vuejs + Vuex 获取复选框状态(选中)

axios - 如何使用 Pinia 商店在 Vue3 SPA 中仅从 API 获取一次数据(在应用程序创建、外部组件或 View 上)

javascript - 确认()取消按钮在 IE11 中不再起作用

javascript - 如何在 Nuxtjs 上放置一个简单的 JS 小部件/小工具 block ?

javascript - v-for 将我的列表渲染为一行多列,而不是一列多行

vuejs3 - 如何在vue3和vite的项目中使用这样的tailwindcss动态类?