vue项目开发遇到需要部分页面要缓存起来,返回时,需要保持上一个页面跳转前的状态。
路由配置
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const router = new Router({
base: '/',
routes: [
{
path: '/',
name: '',
component: resolve => require(['@/views/home'], resolve),
meta: {
requiresAuth: false,
showPage: false,
keepAlive: false
}
}, {
path: '/videoList',
name: '',
component: resolve => require(['@/views/videoList'], resolve),
meta: {
requiresAuth: false,
showPage: false,
keepAlive: true
}
}, {
path: '/videoDetail',
name: '',
component: resolve => require(['@/views/videoDetail'], resolve),
meta: {
requiresAuth: false,
showPage: false,
keepAlive: false
}
}, {
path: '/detail',
name: '',
component: resolve => require(['@/views/detail'], resolve),
meta: {
requiresAuth: false,
showPage: false,
keepAlive: false
}
}, {
path: '/signBack',
name: '',
component: resolve => require(['@/views/signBack'], resolve),
meta: {
requiresAuth: false,
showPage: false,
keepAlive: false
}
}, {
path: '/sign',
name: '',
component: resolve => require(['@/views/sign'], resolve),
meta: {
requiresAuth: false,
showPage: false,
keepAlive: false
}
}, {
path: '/test',
name: '',
component: resolve => require(['@/views/test'], resolve),
meta: {
requiresAuth: false,
showPage: false,
keepAlive: false
}
},
]
})
router.beforeEach((to, from, next) => {
console.log(to)
if (to.meta.requiresAuth) {
if (!localStorage.getItem('token')) {
next('/login')
} else {
next()
}
} else {
next()
}
})
//获取原型对象上的push函数
const originalPush = Router.prototype.push
//修改原型对象中的push方法
Router.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}
export default router
配置app.vue
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>