peg*_*ido 12 typescript vue.js vue-composition-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 }
}
})
Run Code Online (Sandbox Code Playgroud)
在这个简单的例子中,我声明了两个引用和一个计算属性来连接两者。VSC 告诉我计算属性正在返回ReadOnly类型......但我无法让它工作。
acm*_*cme 19
有两种不同的类型。
如果您的计算道具是只读的:
const nameAndCountry: ComputedRef<string> = computed((): string => `The movie name is ${movieName.value} from ${country.value}`);
Run Code Online (Sandbox Code Playgroud)
如果它有一个 setter 方法:
const nameAndCountry: WritableComputedRef<string> = computed({
get(): string {
return 'somestring'
},
set(newValue: string): void {
// set something
},
});
Run Code Online (Sandbox Code Playgroud)
我相信你应该使用泛型:
const movieName = ref<string>("Relatos Salvajes")
const country = ref<string>("Argentina")
const nameAndCountry = computed<string>(
() => `The movie name is ${movieName.value} from ${country.value}`
)
Run Code Online (Sandbox Code Playgroud)
https://vuejs.org/guide/typescript/composition-api.html#typing-compulated
| 归档时间: |
|
| 查看次数: |
6415 次 |
| 最近记录: |