Vue & Typescript 組件傳遞數組問題

問題是要區分數組是null還是空或者有值,對應的顯示會不同。null時什麼都不顯示,空數組是顯示查找結果爲空,有值顯示列表。

由於查找的過程在父組件進行,需要把數據傳遞給子組件,在子組件中用prop進行聲明。那麼這個數組的初始狀態怎麼設置呢?

一開始是在子組件中用@Prop設置默認值null:@Prop({type: Array, default: () => null}),然後父組件把數組初始化爲[]。但是這樣設置不會起作用,因爲父組件把變量設置成[]以後,子組件中的@Prop默認值不會起作用,只有父組件傳遞過來的值爲undefined時,默認值纔會起作用

那麼在父組件把變量初始化成undefined就行了嗎? 例如:

private datasets: Dataset[] | undefined = undefined;

不行! 這樣是不會報錯,並且數組也會正常初始化成null,但是瀏覽器運行的時候會有warn(vue.runtime.esm.js?2b0e:619 [Vue warn]: Property or method "datasets" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.)出來,因爲在父組件模板裏使用了這個變量

<dataset-results :datasets="datasets"></dataset-results>

所以最終的解決辦法只能是在父組件中初始化數組爲null,然後子組件中的默認值設置將不會起作用

private datasets: Dataset[] | null = null;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章