Vue3 Reactive 值未按预期更新

Riz*_*han 2 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 }

}

Run Code Online (Sandbox Code Playgroud)

然后我将 is 导入到一个显示它的 vue 组件中

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

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

Run Code Online (Sandbox Code Playgroud)

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}
})

Run Code Online (Sandbox Code Playgroud)

rit*_*its 5

移至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 };
}
Run Code Online (Sandbox Code Playgroud)

当它在里面并且您导入/调用时,它每次TitleComponent()都会创建一个新实例。obj