利用keep-alive 緩存須要緩存的頁面vue
在app.vue中改寫router-view緩存
<keep-alive> <router-view> <!-- 這裏是會被緩存的視圖組件,好比 page1,page2 --> </router-view> </keep-alive>
在router/index.js中添加路由元信息,設置須要緩存的頁面app
routes: [{ path: '/', name: 'index', component: index, meta: { keepAlive: true, //此組件須要被緩存 } }, { path: '/page1', name: 'page1', component: page1, meta: { keepAlive: true, //此組件須要被緩存 } }, { path: '/page2', name: 'page2', component: page2, meta: { keepAlive: true, // 此組件須要被緩存 } }, { path: '/page3', name: 'page3', component: page3, meta: { keepAlive: true, // 此組件須要被緩存 } } ]
鉤子函數的執行順序ide
不使用keep-alive
beforeRouteEnter --> created --> mounted --> destroyed函數
使用keep-alive
beforeRouteEnter --> created --> mounted --> activated --> deactivated
再次進入緩存的頁面,只會觸發beforeRouteEnter -->activated --> deactivated 。created和mounted不會再執行。咱們能夠利用不一樣的鉤子函數,作不一樣的事。務必理解上述鉤子函數的執行時機和執行順序,本教程的核心就依賴於此鉤子函數
activated和deactivated是使用keep-alive後,vue中比較重要的兩個鉤子函數,建議詳細瞭解下。學習
在組件中,主要是在activated鉤子函數中判斷是否使用緩存3d
activated() {
//使用緩存,直接跳過
if(不須要緩存,則執行相應邏輯){code
}component
},router
文末 分享一些技術學習視頻資料:https://pan.baidu.com/s/13dbR69NLIEyP1tQyRTl4xw