Vue 3 does not update getter



我正在更新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值。

现在进入有趣的部分

在ve2上,我可以这样做:

<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秒在屏幕上更新一次,并按预期工作。但是,当我用下面的代码更改为ve3时,它不再工作了

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

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

我使用最新的vue3.1.5vue-class-component8.0.0-rc.1

你可能应该让它响应,让Vue知道它的值可以被更新,看这里

答案可以在这篇文章中找到:对Vue组件外部创建的对象所做的更改不会被Vue 3检测到

基本上,我需要在服务

中围绕对象封装reactive
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 };

最新更新