27

我正在使用新的 Vue 插件来使用组合 API 和 TypeScript,但有些东西我不太了解。

我应该如何键入计算属性?

import Vue from 'vue'
import { ref, computed, Ref } from '@vue/composition-api'

export default Vue.extend({
  setup(props, context) {

    const movieName:Ref<string> = ref('Relatos Salvajes')
    const country:Ref<string> = ref('Argentina')

    const nameAndCountry = computed(() => `The movie name is ${movieName.value} from ${country.value}`);

    return { movieName, country, nameAndCountry }
  }
})

在这个简单的示例中,我声明了两个 ref 和一个计算属性来连接两者。VSC 告诉我计算属性正在返回ReadOnly类型......但我无法让它工作。

4

2 回答 2

45

有两种不同的类型。

如果您的计算道具是只读的:

const nameAndCountry: ComputedRef<string> = computed((): string => `The movie name is ${movieName.value} from ${country.value}`);

如果它有一个setter方法:

const nameAndCountry: WritableComputedRef<string> = computed({
  get(): string {
    return 'somestring'
  },
  set(newValue: string): void {
    // set something
  },
});
于 2020-10-09T14:07:51.887 回答
1

我相信你应该使用泛型:

const movieName = ref<string>("Relatos Salvajes")
const country = ref<string>("Argentina")

const nameAndCountry = computed<string>(
  () => `The movie name is ${movieName.value} from ${country.value}`
)
于 2021-11-14T06:40:38.403 回答