路由的类别
路由主要由两个字段组成:path 和 component
普通路由
{
path: '/main',
component: Main
}
动态路由
{
path: '/main/:id', // /main/1 /main/2
component: Main
}
嵌套路由
{
path: '/main',
component: Main,
children:[
{
path: 'children',
component: MainChildren
}
]
}
/main/children
// App.vue
<div>
<div>I am App component</div>
<router-view></router-view> // Main.vue
</div>
// Main.vue
<div>
<div>I am main component</div>
<router-view></router-view>
</div>
路由的重定向
[
{
path: '', // localhost:8080
redirect: '/main'
},
{
path: '/main', // // localhost:8080/main
component: Main,
}
]
路由的导航
router-link
<router-link to="/main"></router-link>
编程式导航
push
这个方法会向 history 栈添加一个新的记录,所以,当用户点击浏览器后退按钮时,则回到之前的 URL
this.$router.push('/main')
this.$router.push({name:'main'})
this.$router.push({path:'/main'})
replace
不会向 history 栈添加一个新的记录,而是替换当前路由;
this.$router.replace('/main')
go
根据你的 history 栈 来的,如果是-1,表明就是返回上一级。
this.$router.go(-1)
路由的传参
params
this.$router.push('/main/${id}') //id会默认塞到params对象的 id属性值里面
this.$router.push({
name: 'main',
params:{
id: 'mockid'
}
})
<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>
this.$route.params.id
params里传递的参数在url是不可见的,类似post
query
this.$router.push({
name: 'main',
query:{
id: 'mockid'
}
})
this.$route.query.id
params里传递的参数在url是可见的,类似get
http://localhost:8080/main?id=mockid
监听路由参数的变化
当我们的参数发生变化时,我们如何获取到最新的参数,再做出相对应的业务相应?
比如: /main/id1 -> /main/id2
watch
访问$route我们的当前路由,获取到里面的参数
watch:{
$route:{
handler(from, to){
console.log(this.$route.params.id)
console.log(this.$route.query.id)
},
immediate: true // 初始化也会触发这个handler
}
}
beforeRouteUpdate
组件内的路由守卫方法
beforeRouteUpdate(to, from, next){
console.log(this.$route.params.id)
console.log(this.$route.query.id)
next()
}
与watch $route的功能一致,区别就是:
- beforeRouteUpdate不能监听初始化的值,watch可以通过immediate属性监听到初始化的值
- beforeRouteUpdate可以拦截next(),watch不行
路由的守卫
全局守卫
const routes=[
{path: '/login', component: Login},
{path: '/main', component: Main, meta: { needLogin: true }}
]
const router = new VueRouter({
routes
})
// 访问/main
router.beforeEach(to, from, next){
const targetIsLogin = false // 写死逻辑:没有login
const needLogin = from.meta.needLogin
if(needLogin && targetIsLogin){
next()
}else{
next('/login')
}
}
局部守卫
属性
beforeRouteEnter(to, from, next) 当路由进入的时候,会触发这个方法;
beforeRouteUpdate(to, from, next) 当路由参数发生改变,但是还是在当前路由,会触发这个方法
beforeRouteLeave(to, from, next) 当路由离开的时候,会触发这个方法
举例
/main -> /user
Main组件,beforeRouteLeave
User组件,beforeRouteEnter
/main/id1 -> /main/id2
Main组件, beforeRouteUpdate