Vue Router 配合 keep-alive 不生效的問題及解決方案
其實這個不生效的問題根本也不算一個問題,犯的錯和寫錯單詞差不多,但是也是一時上頭沒發(fā)現(xiàn),所以記錄一下,如果遇到同樣的問題,也希望可以幫助你早點看到這個哭笑不得的錯誤,哈哈哈
問題說明
- 這里我寫了一個非常簡單的demo來復(fù)現(xiàn)我的問題,我的問題場景出自于一個后臺管理系統(tǒng),我在 app.vue 中使用了 router-view 標簽,來展示 layout 和其他一級路由,然后在 layout 下的 main 區(qū)域使用了一個 router-view 來展示通過菜單欄切換的子路由
- 問題就出在這里了,我把 keep-alive 寫在了 app.vue 下的 router-view 位置,然后子路由中需要緩存的組件,就無法實現(xiàn)緩存,當時讓我還以為是什么bug,但是也沒發(fā)現(xiàn)什么問題,最后看官網(wǎng)也是這樣使用的,最后在思考一段時間后點開 router 文件,猛然驚醒,寫錯了位置
案例復(fù)現(xiàn)
demo 結(jié)構(gòu)
1.首先看一下我寫的簡單 demo

2.效果很簡單,點擊切換路由,切換的這個路由是子路由,路由結(jié)果如下:
const routes = [
{
path: '/',
name: 'home',
component: () => import('@/components/HomeView.vue'),
children: [
{
path: 'about',
component: () => import('@/views/AboutView.vue')
},
{
path: 'message',
component: () => import('@/views/MessageView.vue')
}
]
}
]3.這些我就不做贅述了,都非常簡單
4.app.vue 文件代碼如下:
<template>
<div>
<router-view></router-view>
</div>
</template>
<script>
export default {}
</script>
<style scoped></style>5.看了這個之后,在展示一下一級路由 HomeView,如下:
<template>
<div class="home-container">
<div class="header">
<div class="tabs">
<span
class="tab"
v-for="item in tabList"
:key="item.path">
<router-link :to="item.path">{{ item.name }}</router-link>
</span>
</div>
</div>
<div class="main">
<!-- 展示子路由的路由視圖 -->
<router-view></router-view>
</div>
</div>
</template>
<script>
export default {
data() {
return {
tabList: [
{ name: '關(guān)于', path: '/about' },
{ name: '留言', path: '/message' }
]
}
}
}
</script>
<style lang="less" scoped>
.home-container {
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
.header {
height: 70px;
display: flex;
align-items: center;
justify-content: center;
border-bottom: 1px solid #666;
.tab {
margin-right: 20px;
font-size: 20px;
}
}
.main {
flex: 1;
width: 100%;
}
}
</style>6.其余兩個頁面和本次問題關(guān)系不大,而且都很簡單就不展示了
問題復(fù)現(xiàn)和解決
1.現(xiàn)在我打需求是在切換頁面的時候,可以讓留言頁面輸入的內(nèi)容進行緩存
2.我們在 app.vue 下是使用 keep-alive,看看效果
<template> <div> <!-- MessageVue 是留言組件的 name 屬性 --> <keep-alive :include="['MessageVue']"> <router-view></router-view> </keep-alive> </div> </template>
3.效果如圖:

4.現(xiàn)在是無法生效的,然后我們放在 HomeView 的路由出口上,如下:
<template>
<div class="home-container">
<div class="header">
<div class="tabs">
<span
class="tab"
v-for="item in tabList"
:key="item.path">
<router-link :to="item.path">{{ item.name }}</router-link>
</span>
</div>
</div>
<div class="main">
<keep-alive :include="['MessageVue']">
<router-view></router-view>
</keep-alive>
</div>
</div>
</template>5.現(xiàn)在在看一下效果,如圖:

6.解決還是非常簡單的,謹以此文記錄我這次馬虎的錯誤
到此這篇關(guān)于Vue Router 配合 keep-alive 不生效的問題的文章就介紹到這了,更多相關(guān)Vue Router keep-alive 不生效內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue.js獲取數(shù)據(jù)庫數(shù)據(jù)實例代碼
本篇文章主要介紹了vue.js獲取數(shù)據(jù)庫數(shù)據(jù)實例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05
vuex提交state&&實時監(jiān)聽state數(shù)據(jù)的改變方法
今天小編就為大家分享一篇vuex提交state&&實時監(jiān)聽state數(shù)據(jù)的改變方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09

