先閱讀 【Vue 2 組件基礎】中的初步了解動態組件。
動態組件與keep-alive
我們知道動態組件使用is
屬性和component
標簽結合來切換不同組件。
下面給出一個示例:
<!DOCTYPE html>
<html><head><title>Vue 動態組件</title><script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
</head><body><div id="app"><!-- tab 標簽頁 --><div><button @click="tab = 'home'">首頁</button><button @click="tab = 'posts'">文章</button></div>父組件count: {{count}}<!-- 動態組件 --><component :is="tab" @increment="count=$event"></component></div><script>// 注冊組件Vue.component('home', {data: function () {return {count: 0}},template: `<div><div>首頁內容</div><div>子組件count: {{count}}</div><button @click="count++;$emit('increment', count)">點擊了{{count}}次</button></div>`,});Vue.component('posts', {template: '<div>文章內容</div>'});var vm = new Vue({el: '#app',data: {tab: 'home',count: 0},});</script>
</body></html>
<script>
看代碼可以知道父組件的count會在子組件count更新后變為子組件的count值。但我們切換組件后再切換回來,會發現父組件count沒變,子組件count變為初始值。這是因為,每次切換組件都會創建當前組件的新實例。
那怎么保存先前組件的狀態呢?
Vue提供了keep-alive
組件。我們使用該元素將要緩存的組件包裹起來。讓我們看看效果:
<keep-alive><component :is="tab" @increment="count=$event"></component>
</keep-alive>
成功解決問題!
了解更多keep-alive組件的細節。
異步組件
異步組件是一種加載組件的方式,它允許我們將組件的加載推遲到需要時再進行,以提高應用程序的性能和加載速度。
我們可以通過不同的方式使用異步組件。
1.工廠函數
使用Vue.component
方法來定義一個異步組件工廠函數:
Vue.component('async-component',function(resolve,reject){//模擬異步加載,延遲一段時間后解析組件setTimeout(function(){resolve({template:'<div><h2>Async Component Content</h2></div>'})},1000)
})
使用Vue.component
方法結合webpack的code-splitting來定義一個異步組件工廠函數:
Vue.component('async-component',function(resolve,reject){//這個特殊的require語法會告訴webpack自動將編譯后的異步組件拆分成不同的塊require('./AsyncComponent.vue',resolve)
})
在上面代碼中,async-component
是你定義異步組件的名字,后面的工廠函數有兩個參數:resolve
和reject
。resolve
是一個函數,異步加載成功時會調用它。reject
則是在異步加載失敗時調用。
2.Vue.component+動態導入+webpack 2的代碼分割+ES2015的模塊語法
Vue.component(`async-webpack-example`,()=>import('./my-async-component')
);
()=>import('./my-async-component')
返回一個Promise,Vue會根據Promise的狀態來自動處理異步加載和渲染的過程。
3.局部注冊+動態導入
new Vue({components:{'my-component':()=>import('./my-async-component')}
})
處理加載狀態
異步組件工廠函數可以返回一個對象,該對象包含有關異步組件加載、加載中、加載失敗等情況的配置信息,這種方式允許你更加精細地控制異步組件地加載和渲染過程。下面是這種格式的異步組件配置對象的詳細解釋:
const AsyncComponent=()=({//需要加載的組件component:import('./MyComponent.vue'),//異步加載時使用的組件loading:LoadingComponent,//加載失敗時使用的組件error:ErrorComponent,//展示加載時組件的延遲時間,默認值是200(毫秒)delay:200,// 如果提供了超時時間且組件加載也超時了,// 則使用加載失敗時使用的組件。默認值是:`Infinity`,即沒有超時限制timeout: 3000
})