VueJS中的類型引用提供/注入功能
P粉441076405
P粉441076405 2023-09-04 16:34:30
<p>我正在嘗試從父元件提供一個類型化的 ref,並將其註入到子元件中。 </p> <p>我不確定是否理解了VueJS文檔,但這是我想出來的。 </p> <pre class="brush:php;toolbar:false;">import type { Ref } 從 'vue' import type { InjectionKey } from 'vue' import type DocumentSet from '@/types/DocumentSet' const documentSet = Symbol() as InjectionKey<{ documentSet: Ref<DocumentSet>, update: () => void }> export default documentSet</pre> <p>所以,任務是提供一個類型化的物件(在我的情況下是documentSet),以及一個更新它的函數。 </p> <p>現在,在父元件中我有這樣的程式碼:</p> <pre class="brush:php;toolbar:false;">import dsKey from '@/injectionKeys/documentSet' import type DocumentSet from '@/types/DocumentSet' … const documentSet = ref<DocumentSet | null>(null) provide(dsKey, { documentSet, update: () => console.log('update') })</pre> <p>而在子元件中,我有這樣的程式碼:</p> <pre class="brush:php;toolbar:false;">import dsKey from '@/injectionKeys/documentSet' const ds = inject(dsKey) const documentSet = ds?.documentSet</pre> <p>問題是,由於有很多樣板程式碼,我覺得自己做錯了什麼。例如,我無法理解為什麼要重構ds對象,像這樣:</p> <pre class="brush:php;toolbar:false;">const { documentSet } = ds</pre> <p>是否有可能縮短程式碼,而不是寫入<code>ds?.documentSet</code>,尤其是如果我確定ds應該存在(沒有它,我不會渲染子元件)</p> <p>如果我這樣寫<code>const { documentSet } = inject(dsKey)</code>,會出現以下錯誤:</p> <p><code>TS2339: 類型「{ documentSet: Ref ;」上不存在屬性「documentSet」更新:() => 無效; } |未定義'.</code></p> <p>這個想法是因為我想消除子組件中的重複:</p> <pre class="brush:php;toolbar:false;"><DocumentSetInfo :documentSet="documentSet" /> <DocumentSetMemos :documentSet="documentSet" /> <DocumentSetPrograms :documentSet="documentSet" /> <DocumentSetPetition :documentSet="documentSet" /> <DocumentSetPassRequests :documentSet="documentSet" /> <DocumentSetReport :documentSet="documentSet" /> <DocumentSetReceptionNotices :documentSet="documentSet" /></pre></p>
P粉441076405
P粉441076405

全部回覆(1)
P粉446800329

你可以將它放入一個可組合項中,該項目提供了一個處理提供的函數provde和一個處理注入的函數use*:

const CurrentDocumentSetKey = Symbol() as InjectionKey<{
  documentSet: Ref,
  update: () => void
}>

export function provideCurrentDocumentSet(documentSet:DocumentSet, update: () => any){
  provide(CurrentDocumentSetKey, {documentSet, update})
}

export useCurrentDocumentSet(){
  const ds = inject(CurrentDocumentSetKey)
  if (!ds) throw new Error('No current DocumentSet provided')
  return ds
}

現在你只需要在父元件中呼叫provideCurrentDocumentSet(),所有子元件只需要執行以下操作:

const {documentSet, update} = useCurrentDocumentSet()

你甚至不需要匯出InjectionKey,元件也不需要知道它。 (例如Vuetify也是這樣做的,例如這裡

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!