簡體   English   中英

Vue.js + Typescript:如何將@Prop 類型設置為字符串數組?

[英]Vue.js + Typescript: How to set @Prop type to string array?

@Prop裝飾器的type屬性設置為Array<string>的正確方法是什么? 甚至有可能嗎?

我只能將它設置為沒有string Array ,如下所示:

<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<string>甚至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

道具應該按照文檔中的描述進行注釋。

您應該添加as PropType<string[]>

<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>

默認Array s 和Object s 應始終從工廠函數( source )返回。 這避免(意外地)在多個組件實例之間共享一個屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM