【问题标题】:How to type a computed property in the new composition API?如何在新的组合 API 中键入计算属性?
【发布时间】:2020-07-06 10:25:09
【问题描述】:

我正在使用新的 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 类型......但我无法让它工作。

【问题讨论】:

  • 但我做不到 - 究竟是什么?从您的代码中,我希望可以正确推断出类型。
  • 我的意思是,我应该在nameAndCountry const 中添加什么类型才能正确输入。这是我们应该在具有计算值的 TS 应用程序中做的事情吗?
  • 我希望它类似于 Ref>。你不需要在这里添加类型,它是推断出来的。也不需要参考,它们被明确地推断为字符串。确保 TS 处于严格模式,以便在需要类型被跳过时收到警告。

标签: typescript vue.js vue-composition-api


【解决方案1】:

有两种不同的类型。

如果你的计算属性是只读的:

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
  },
});

【讨论】:

【解决方案2】:

我相信你应该使用泛型:

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

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

【讨论】:

    猜你喜欢
    • 2020-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-11
    • 2021-07-11
    • 2020-04-04
    • 1970-01-01
    • 2019-12-27
    相关资源
    最近更新 更多