簡體   English   中英

如何將數組設置為道具的默認值(Vue組合api + Typescript)

[英]How to set array as default value on props (Vue composition api + Typescript)

使用 Vue 3 (composition api) + Typescript,我試圖在使用接口定義道具后在道具上設置默認值。 當我嘗試在其中一個道具上設置默認值[]時,出現 typescript 錯誤。 如何設置默認的空數組?

<script setup lang="ts">

interface IProps {

  title: string;
  things: any[];
  productUrl: any;
}

const props = withDefaults(defineProps<IProps>(), {
  title: "",
  things: [],            //<-- error (se below)
  productUrl: "",
});

錯誤:

Type 'never[]' is not assignable to type '(props: Readonly<IProps>) => any[]'.

它還說:

The expected type comes from property 'things' which is declared here on type 
'InferDefaults<Readonly<IProps>>'

Object 或數組屬性默認值必須從工廠返回 function。 Vue 文檔在 道具驗證下提到了這一點

const props = withDefaults(defineProps<IProps>(), {
  title: "",
  things: () => [],
  productUrl: "",
});

您應該使用 function 返回空數組:

<script setup lang="ts">

interface IProps {

  title: string;
  things: any[];
  productUrl: any;
}

const props = withDefaults(defineProps<IProps>(), {
  title: "",
  things: ()=>[], 
  productUrl: "",
});

對於標准語法:

const props =defineProps({
  things:{
      type:Array,
      required:true,
      default:()=>[]
    }
})

暫無
暫無

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

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