1.获取当前的路由,并且实现后退功能
export default {
computed: {
username () {
//获取当前路由
return this.$route.params.username
}
},
methods: {
//后退功能
goBack () {
window.history.length > 1
? this.$router.go(-1)
: this.$router.push('/')
}
}
}
注意:this.$route是当前路由,this.$router是指整个路由。
2.动态路由
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
<p>
<router-link to="/user/foo">/user/foo</router-link>
<router-link to="/user/bar">/user/bar</router-link>
</p>
<router-view></router-view>
</div>
const User = {
template: `<div>User {{ $route.params.id }}</div>`
}
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User }
]
})
const app = new Vue({ router }).$mount('#app')
上面已经说了,this.$route是指当i当前路由,this.$route会返回一个包括所有的在路由中定义的:后面的键值对集合的对象:
3.路由复用
const User = {
template: '...',
beforeRouteUpdate (to, from, next) {
// react to route changes...
// don't forget to call next()
}
}
4.嵌套路由
嵌套路由需要在参数中加上children
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User,
children: [
{
// 当 /user/:id/profile 匹配成功,
// UserProfile 会被渲染在 User 的 <router-view> 中
path: 'profile',
component: UserProfile
},
{
// 当 /user/:id/posts 匹配成功
// UserPosts 会被渲染在 User 的 <router-view> 中
path: 'posts',
component: UserPosts
}
]
}
]
})
https://router.vuejs.org/zh/guide/essentials/navigation.html