路由对象
fullPath: "/"
hash: ""
href: "/"
matched: [{…}]
meta: {}
name: undefined
params: {}
path: "/"
query: {}
redirectedFrom: undefined
[[Prototype]]: Object
导航守卫
全局前置守卫
router.beforeEach((to,from,next)=>{
document.title = to.meta.title
next()
})
全局解析守卫
router.beforeResolve((to,from,next)=>{
next()
})
全局后置钩子
router.afterEach((to,from,failure)=>{
if (!failure) sendToAnalytics(to.fullPath)
})
路由独享守卫
beforeEnter(to,from,next)
-------------------------------------------
const routes = [
{
path:"/user/:userid",
name:"user",
beforeEnter: (to, from, next) => {
next()
},
component:() =>import("@/components/user"),
}
]
组件内的守卫
beforeRouteEnter(to, from) {
}
beforeRouteUpdate(to, from) {
}
beforeRouteLeave(to, from) {
}
记录状态
单个组件
App.vue
--------------------------------------
<template>
<div>
<router-link to="/home">home</router-link>
<router-link to="/about">about</router-link>
<router-view v-slot="{ Component }">
<keep-alive>
<component :is="Component" />
</keep-alive>
</router-view>
</div>
</template>
router.js
----------------------------------------------
const routes = [
{
path:"/about",
meta:{
title:"关于",
keepAlive:true
},
component:() =>import("@/components/about")
}
]
App.vue
-------------------------------------------------
<template>
<div>
<router-link to="/home">home</router-link>
<router-link to="/about">about</router-link>
<router-view v-slot="{ Component }">
<keep-alive >
// 保留状态的在这里渲染 $route.meta.keepAlive为true
<component :is="Component" v-if="$route.meta.keepAlive"/>
</keep-alive>
// 没有保留状态的在这里渲染 $route.meta.keepAlive为false
<component :is="Component" v-if="!$route.meta.keepAlive"/>
</router-view>
</div>
</template>
多层组件
router.js
----------------------------------------------------------
const routes = [
{
path:"/home",
component:() =>import("@/components/home"),
alias:"/",
meta:{
title:"主页",
keepAlive:true
},
children:[
{
path:"news",
component:() =>import("@/components/homenews")
},
{
path:"acg",
component:() =>import("@/components/homeacg")
}
]
}
]
App.vue
--------------------------------------------------------------
<router-view v-slot="{ Component }">
<keep-alive >
<component :is="Component" v-if="$route.meta.keepAlive"/>
</keep-alive>
<component :is="Component" v-if="!$route.meta.keepAlive"/>
</router-view>
home.vue
---------------------------------------------------------------
<script>
export default {
name:"home",
data() {
return {
path:'/home'
}
},
activated() {
this.$router.push(this.path)
},
beforeRouteLeave (to, from, next) {
this.path = from.path
next()
}
}
</script>