動態組件和異步組件其實在實際開發中是經常需要用到的。之前自己的做法總是根據選中的狀態去判斷該顯示的內容,一直忽略了vue里面本身就有的這么個功能
基本使用:
<template> <div> <el-button-group> <el-button v-for='(btn, index) in btnGroup' :key="index" :class="{active:btn.disabled}" @click='change(index)'>{{btn.name}} </el-button> </el-button-group> <div> <component :is='currentCom'></component> </div> </div> </template> <script> import Childs1 from './Childs1' import Childs2 from './Childs2' import Childs3 from './Childs3' import Childs4 from './Childs4' export default { name:'Parent', components:{ Childs1, Childs2, Childs3, Childs4 }, data() { return { btnGroup: [ {name: 'Childs1', disabled: true}, {name: 'Childs2', disabled: false}, {name: 'Childs3', disabled: false}, {name: 'Childs4', disabled: false}, ], currentCom:'Childs1' } }, methods: { change(index){ let pre = Number(this.currentCom[this.currentCom.length -1]); this.btnGroup[pre -1].disabled = false; this.btnGroup[index].disabled = true; this.currentCom = 'Childs' + (index + 1); } } } </script> <style scoped> .active{ background-color: red; } </style>
is的值可以食一個已經注冊的組件的名字或者一個組件的選擇對象
如果我們需要頻繁的切換頁面,可以使用keep-alive緩存當前組件的狀態
<template> <div> <el-button-group class='btn-group'> <el-button v-for='(btn, index) in btnGroup' :key="index" :class="{active:btn.disabled}" @click='change(index)'> {{btn.name}} </el-button> </el-button-group> <div style='padding-top:100px;'> <keep-alive> <component :is='currentCom'></component> </keep-alive> </div> </div> </template> <style scoped> .btn-group{ position:fixed; } .active{ background-color: red; } </style>
提示:因為緩存的組件只需要建立一次,所以如果我們要在每次進入組件的鈎子函數里面做相應的操作的時候,會出現問題,必須明確使用的場景
異步組件
異步組件存在的異議,在於加載一個體量很大的頁面時,如果我們不設置加載的優先級的話,那么頁面在加載視屏等信息的時候會非常占用時間,然后阻塞后面主要信息的加載。官網上面是這么說明的
在大型應用中,我們可能需要將應用分割成小一些的代碼塊,並且只在需要的時候才從服務器加載一個模塊。為了簡化,Vue 允許你以一個工廠函數的方式定義你的組件,這個工廠函數會異步解析你的組件定義。Vue 只有在這個組件需要被渲染的時候才會觸發該工廠函數,且會把結果緩存起來供未來重渲染。
Vue.component('async-webpack-example', function (resolve) { // 這個特殊的 `require` 語法將會告訴 webpack // 自動將你的構建代碼切割成多個包,這些包 // 會通過 Ajax 請求加載 require(['./my-async-component'], resolve) })
也可以在工廠函數中返回一個 Promise
Vue.component( 'async-webpack-example', // 這個動態導入會返回一個 `Promise` 對象。 () => import('./my-async-component') )
當使用局部注冊的時候,你也可以直接提供一個返回 Promise
的函數:
new Vue({ // ... components: { 'my-component': () => import('./my-async-component') } })
這里的異步組件工廠函數也可以返回一個如下格式的對象:(2.3.0新增)
const AsyncComponent = () => ({ // 需要加載的組件 (應該是一個 `Promise` 對象) component: import('./MyComponent.vue'), // 異步組件加載時使用的組件 loading: LoadingComponent, // 加載失敗時使用的組件 error: ErrorComponent, // 展示加載時組件的延時時間。默認值是 200 (毫秒) delay: 200, // 如果提供了超時時間且組件加載也超時了, // 則使用加載失敗時使用的組件。默認值是:`Infinity` timeout: 3000 })