【问题标题】:Vue3 Reactive value is not updating as expectedVue3 反应值未按预期更新
【发布时间】:2021-07-03 21:48:14
【问题描述】:

我有这个 .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}
})

【问题讨论】:

    标签: javascript vuejs3


    【解决方案1】:

    obj 移出export const TitleComponent = () =&gt; {}

    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 的新实例。

    【讨论】:

    • 虽然这可以正常工作,但它不会更新 UI...如果您通过控制台记录它更改的值,而不是您在 HTML 中看到的值
    • @RizaKhan 我刚刚在codesandbox.io 中复制了它并且它更新了。唯一的区别是我将defineComponent({}) 中的内容包裹在setup() {} 中。
    • 你碰巧有这个codeandbox的链接吗?
    猜你喜欢
    • 2018-03-03
    • 2021-11-22
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多