路由
安装 vue-router
起步
<router-link to="/foo">Go to Foo</router-link> <router-link to="/bar">Go to Bar</router-link> <router-view></router-view>
const Foo = { template: '<div>foo</div>' } const Bar = { template: '<div>bar</div>' } const routes = [ { path: '/foo', component: Foo }, { path: '/bar', component: Bar } ] const router = new VueRouter({ routes // (缩写) 相当于 routes: routes }) const app = new Vue({ router }).$mount('#app')
通过this.$router访问路由器
export default { computed: { username () { return this.$route.params.username } }, methods: { goBack () { window.history.length > 1 ? this.$router.go(-1) : this.$router.push('/') } } }
动态路由
{ path: '/user/:id', component: User }
像/user/bar和/user/foo都能映射到相同的路由
参数会被设置到this.$router.params中
const User = { template: '<div>User {{ $route.params.id }}</div>' }
可以设置多端参数
// 模式 /user/:username/post/:post_id // 匹配路径 /user/evan/post/123 // $router.params { username: 'evan', post_id: '123' }
从/user/foo到/user/bar 原来的组件实例会被复用。因为两个路由都渲染同一个组件。也就是组件不会销毁和创建,而是复用,也就是组件的生命周期钩子不会再调用
可以使用watch检测$router对象
const User = { template: '...', watch: { '$route' (to, from) { // 对路由变化作出响应... } } }
捕获所有路由或404 Not found路由
扫描二维码关注公众号,回复:
6107195 查看本文章
匹配所有路由
path: '*'
匹配'/user-*'开头的路由
path: '/user-*'
当使用通配符时,$router.params会添加名为pathMatch参数
// 给出一个路由 { path: '/user-*' } this.$router.push('/user-admin') this.$route.params.pathMatch // 'admin' // 给出一个路由 { path: '*' } this.$router.push('/non-existing') this.$route.params.pathMatch // '/non-existing'
嵌套路由
我们在User组件中添加router-view
const User = { template: ` <div class="user"> <h2>User {{ $route.params.id }}</h2> <router-view></router-view> </div> ` }
路由配置
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 } ] } ] })
编程式导航