Vue.js的動態(tài)組件模板的實現(xiàn)
組件并不總是具有相同的結構。有時需要管理許多不同的狀態(tài)。異步執(zhí)行此操作會很有幫助。
實例:
組件模板某些網(wǎng)頁中用于多個位置,例如通知,注釋和附件。讓我們來一起看一下評論,看一下我表達的意思是什么。
評論現(xiàn)在不再僅僅是簡單的文本字段。您希望能夠發(fā)布鏈接,上傳圖像,集成視頻等等。必須在此注釋中呈現(xiàn)所有這些完全不同的元素。如果你試圖在一個組件內執(zhí)行此操作,它很快就會變得非?;靵y。

處理方式
我們該如何處理這個問題?可能大多數(shù)人會先檢查所有情況,然后在此之后加載特定組件。像這樣的東西:
<template> <div class="comment"> // comment text <p>...</p> // open graph image <link-open-graph v-if="link.type === 'open-graph'" /> // regular image <link-image v-else-if="link.type === 'image'" /> // video embed <link-video v-else-if="link.type === 'video'" /> ... </div> </template>
但是,如果支持的模板列表變得越來越長,這可能會變得非?;靵y和重復。在我們的評論案例中 - 只想到支持Youtube,Twitter,Github,Soundcloud,Vimeo,F(xiàn)igma的嵌入......這個列表是無止境的。
動態(tài)組件模板
另一種方法是使用某種加載器來加載您需要的模板。這允許你編寫一個像這樣的干凈組件:
<template> <div class="comment"> // comment text <p>...</p> // type can be 'open-graph', 'image', 'video'... <dynamic-link :data="someData" :type="type" /> </div> </template>
看起來好多了,不是嗎?讓我們看看這個組件是如何工作的。首先,我們必須更改模板的文件夾結構。

就個人而言,我喜歡為每個組件創(chuàng)建一個文件夾,因為可以在以后添加更多用于樣式和測試的文件。當然,您希望如何構建結構取決于你自己。
接下來,我們來看看如何<dynamic-link />構建此組件。
<template>
<component :is="component" :data="data" v-if="component" />
</template>
<script>
export default {
name: 'dynamic-link',
props: ['data', 'type'],
data() {
return {
component: null,
}
},
computed: {
loader() {
if (!this.type) {
return null
}
return () => import(`templates/${this.type}`)
},
},
mounted() {
this.loader()
.then(() => {
this.component = () => this.loader()
})
.catch(() => {
this.component = () => import('templates/default')
})
},
}
</script>
那么這里發(fā)生了什么?默認情況下,Vue.js支持動態(tài)組件。問題是您必須注冊/導入要使用的所有組件。
<template>
<component :is="someComponent"></component>
</template>
<script>
import someComponent from './someComponent'
export default {
components: {
someComponent,
},
}
</script>
這里沒有任何東西,因為我們想要動態(tài)地使用我們的組件。所以我們可以做的是使用Webpack的動態(tài)導入。與計算值一起使用時,這就是魔術發(fā)生的地方 - 是的,計算值可以返回一個函數(shù)。超級方便!
computed: {
loader() {
if (!this.type) {
return null
}
return () => import(`templates/${this.type}`)
},
},
安裝我們的組件后,我們嘗試加載模板。如果出現(xiàn)問題我們可以設置后備模板。也許這對向用戶顯示錯誤消息很有幫助。
mounted() {
this.loader()
.then(() => {
this.component = () => this.loader()
})
.catch(() => {
this.component = () => import('templates/default')
})
},
結論
如果您有一個組件的許多不同視圖,則可能很有用。
- 易于擴展。
- 它是異步的。模板僅在需要時加載
- 。保持代碼干凈。
基本上就是這樣!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Vue實現(xiàn)側邊導航欄于Tab頁關聯(lián)的示例代碼
本文主要介紹了Vue實現(xiàn)側邊導航欄于Tab頁關聯(lián)的示例代碼,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-11-11

