vue.js:计算属性未通过反应式依赖更新来更新

问题描述 投票:0回答:1

我正在尝试创建一个带有 ComputedRef<> 字段的类,并将其对象分配给组件属性。但计算属性没有更新。

/// Student.ts

import { computed, type ComputedRef } from "vue";

export class Student {
    age: number;
    adult: ComputedRef<boolean>;

    constructor(age: number) {
        this.age = age;

        const that = this;
        this.adult = computed(() => that.age >= 18);
    }
}
/// StudentComponent.vue

<script setup lang="ts">
import { Student } from './student';
import { ref } from 'vue';

const props = defineProps<{
    data: Student
}>();
const dataRef = ref(props.data);

</script>

<template>
    <div>age: {{ dataRef.age }}</div>
    <div>adult: {{ dataRef.adult }}</div>
    <button @click="++dataRef.age;">+1</button>
    <button @click="--dataRef.age;">-1</button>
</template>
</script>
/// App.vue

<script setup lang="ts">
import StudentComponent from './StudentComponent.vue';
import { Student } from './student';

const student = new Student(18);

</script>

<template>
    <StudentComponent :data="student"></StudentComponent>
</template>

结果如下:

单击“-1”按钮时,“成人”值不会更改。我该怎么办?

vue.js
1个回答
0
投票

计算值仅在任何引用的“ref”更新时才会更新。由于类属性“age”只是一个数字而不是引用,因此计算属性将不知道何时设置新值。

如果您更新类以使用“age”属性的引用,它应该可以工作:

import { ref, type Ref, computed, type ComputedRef } from "vue";

export class Student {
    age: Ref<number>;
    adult: ComputedRef<boolean>;

    constructor(age: number) {
        this.age = ref(age);
        this.adult = computed(() => this.age.value >= 18);
    }
}

确保使用

studentInstance.age.value = newValue
更新年龄属性。

您还可以“隐藏”您在类中使用带有私有属性的 getter/setter 的 ref 的事实

import {ref, type Ref, computed, type ComputedRef } from 'vue'


export class Student {
  _age: Ref<number>
  adult: ComputedRef<boolean>

  get age() {
    return this._age.value
  }

  set age(newVal: number) {
        this._age.value = newVal
}

  constructor(age: number) {
    this._age = ref(age)
    this.adult = computed(() => this._age.value >= 18)
  }
}

这将让您正常更新值

studentInstance.age = newValue

© www.soinside.com 2019 - 2024. All rights reserved.