Vue.js + Typescript:如何将@Prop 类型设置为字符串数组?

Posted

技术标签:

【中文标题】Vue.js + Typescript:如何将@Prop 类型设置为字符串数组?【英文标题】:Vue.js + Typescript: How to set @Prop type to string array? 【发布时间】:2020-12-27 00:16:50 【问题描述】:

@Prop装饰器的type属性设置为Array<string>的正确方法是什么?有可能吗?

我只能将它设置为Array 而没有string,就像这样:

<script lang="ts">
import  Component, Prop, Vue  from 'vue-property-decorator';

@Component
export default class MyComponent extends Vue 
  @Prop( type: Array, default: [] ) private readonly myProperty!: string[];

</script>

当我尝试将其更改为 Array&lt;string&gt; 甚至 string[] 时,我收到以下错误:

Argument of type ' type: boolean; default: never[]; ' is not assignable 
to parameter of type 'PropOptions<any> | Constructor | Constructor[] | undefined'.

Types of property 'type' are incompatible. Type 'boolean' is not assignable to type 
'(new (...args: string[]) => Function) | (() => any) | (new (...args: never[]) => any) | Prop<any>[] | undefined'.

这个错误信息更让我困惑:为什么现在类型被识别为boolean

【问题讨论】:

【参考方案1】:

应该按照docs 中的说明对道具进行注释。

你应该添加as PropType&lt;string[]&gt;:

<script lang="ts">
import  PropType  from "vue"
import  Component, Prop, Vue  from 'vue-property-decorator';

@Component
export default class MyComponent extends Vue 
  @Prop(
    type: Array as PropType<string[]>, // use PropType
    default: () => [] // use a factory function
  ) private readonly myProperty!: string[];

</script>

默认的Arrays 和Objects 应该总是从工厂函数返回(source)。这样可以避免(意外地)在多个组件实例之间共享一个属性。

【讨论】:

以上是关于Vue.js + Typescript:如何将@Prop 类型设置为字符串数组?的主要内容,如果未能解决你的问题,请参考以下文章

Vue js,使用 TypeScript 从 Vue 中的表单获取数据

typescript 使用Typescript将属性添加到Vue.js中的数组

如何获得 Vue.js 2.0 类型的 TypeScript 与 Visual Studio 一起使用?

将 Typescript 与 Laravel 和 Vue.js 一起使用,导入不使其成为 Vue 组件?

更改编辑模式Vue.js + Typescript后如何专注于输入字段

(如何)我应该在 Vue.js 组件(TypeScript)中使用访问修饰符(公共、私有等)吗?