如何在新的组合 API 中键入计算属性?
·
问题:如何在新的组合 API 中键入计算属性?
我正在使用新的 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类型......但我无法让它工作。
解答
有两种不同的类型。
如果您的计算道具是只读的:
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
},
});
更多推荐

所有评论(0)