javascript - Vue3 Reactive 值未按预期更新

标签 javascript vuejs3

我有这个 .ts 文件:

import { reactive, toRefs } from 'vue'

export const TitleComponent = () => {
  const obj = reactive({
    title: "This should be reactive"
  }) 

  const updateObj = () => {
    obj.title = 'This is now different'
  }
  return {...toRefs(obj), updateObj }

}

然后我将其导入到显示它的 vue 组件中

<template>
  <h1>{{ title }}</h1>
</template>
import { defineComponent } from 'vue'
import { TitleComponent } from 'some/place'

export default defineComponent({
  const { title } = TitleComponent()
  return { title }
})

然后,我在运行该方法的另一个组件中使用函数 updateObj。但它不会更新标题值。给出了什么?

<template>
  <button @click="updateObj">Click Me</button>
</template>

import { defineComponent } from 'vue'
import { TitleComponent } from 'some/place'

export default defineComponent({
  const { updateObj } = TitleComponent()
  return { updateObj}
})

最佳答案

obj 移至 export const TitleComponent = () => {} 之外。

import { reactive, toRefs } from 'vue';

const obj = reactive({
  title: 'This should be reactive'
});

export const TitleComponent = () => {
  const updateObj = () => {
    obj.title = 'This is now different'
  };

  return { ...toRefs(obj), updateObj };
}

当您在其中导入/调用 TitleComponent() 时,它每次都会创建一个 obj 的新实例。

关于javascript - Vue3 Reactive 值未按预期更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66996958/

相关文章:

javascript - 如何让太阳的弧线停在页面的左端?

javascript - 缩略图视频react-native-image-picker

vue.js - Vuetify 自动完成显示 [object Object]

vue.js - Vue Js 添加动态类名

javascript - 添加 require 关键字会破坏原生 JavaScript 函数

javascript - jCal 使用 jQuery

vuejs3 - 如何从代码中关闭 headlessui-vue Popover

vue.js - 升级到 Vue 3 : where to put data and methods?

javascript - 单击带有 javascript/jquery 的链接时显示表单字段

typescript - 我怎样才能专注于 Vue 3 中的动态输入?