【问题标题】:Vue 3 does not update getterVue 3 不更新 getter
【发布时间】:2021-10-07 20:14:13
【问题描述】:

我正在更新 vue2 到 vue3 但遇到这个问题。 我有一个服务叫TService

// T.ts
class T {
  public obj = { value: false };
  constructor() {
    setInterval(() => {
      this.obj.value = !this.obj.value;
    }, 1000);
  }
}

const t = new T();
export { t as TService };

服务很简单,每1秒更新一次obj值。

现在进入有趣的部分

在 vue2 上,我可以这样做:

<template>
  <div> {{ test }} </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from "vue-property-decorator";
import { TService } from './T;

@Component
export default class HelloWorld extends Vue {
  public obj = TService.obj;
  get test() {
    return this.obj.value;
  }
}
</script>

test 值每 1 秒在屏幕上更新一次,并按预期工作。 但是,当我使用以下代码更改为 vue3 时,它不再工作了

<template>
  <div>{{ test }}</div>
</template>

<script lang="ts">
import { Options, Vue } from "vue-class-component";
import { TService } from './T';

@Options({})
export default class HelloWorld extends Vue {
  public obj = TService.obj;
  get test() {
    return this.obj.value;
  }
}
</script>

不知道发生了什么,如果有人能修复我的代码,不胜感激。

我正在使用最新的vue 3.1.5vue-class-component 8.0.0-rc.1

【问题讨论】:

    标签: vue.js vuejs3


    【解决方案1】:

    你可能应该让它反应,以便 Vue 知道它的值可以更新,see here

    【讨论】:

    • 你可以为 vue3 版本修复我上面的代码吗?
    • 已经尝试public obj = reactive(TService.obj);,但仍然没有成功
    【解决方案2】:

    可以在这篇文章中找到答案: Changes made to an object created outside of Vue component are not detected by Vue 3

    基本上我需要在我的服务中围绕我的对象进行响应式包装

    import { reactive } from 'vue'; 
    
    // T.ts
    class T {
      public obj = reactive({ value: false });
      constructor() {
        setInterval(() => {
          this.obj.value = !this.obj.value;
        }, 1000);
      }
    }
    
    const t = new T();
    export { t as TService };
    

    【讨论】:

      猜你喜欢
      • 2021-06-04
      • 1970-01-01
      • 2021-11-13
      • 2021-06-29
      • 2021-10-18
      • 2017-12-24
      • 2022-09-28
      • 2022-12-21
      • 2022-10-24
      相关资源
      最近更新 更多