vue-router 笔记
1、 动态路由匹配
比如:(动态路由的高级匹配)
https://github.com/vuejs/vue-router/blob/next/examples/route-matching/app.js
2、 编程式导航
(1)router.push(…)
使用router.push(…)【等同于<router-link to=”…”>(声明式)】创建,这个方法回向history栈中添加一个新的记录,当用户点击浏览器后退的时候,则返回之前的url
该方法的参数可以是一个字符串路径,或者一个描述地址的对象。
比如:
// 字符串 router.push('home') // 对象 router.push({ path: 'home' }) // 命名的路由,(如果name对应的路径是/user的话,那么相当于/user/123) router.push({ name: 'user', params: { userId: 123 }}) // 带查询参数,变成 /register?plan=private router.push({ path: 'register', query: { plan: 'private' }})
(2)router.replace(location)
跟 router.push
很像,唯一的不同就是,它不会向 history 添加新记录,而是跟它的方法名一样 —— 替换掉当前的 history 记录
(3)router.go(n)
这个方法的参数是一个整数,意思是在 history 记录中向前或者后退多少步,类似 window.history.go(n)
比如:
// 在浏览器记录中前进一步,等同于 history.forward()
router.go(1)
// 后退一步记录,等同于 history.back()
router.go(-1)
// 前进 3 步记录
router.go(3)
// 如果 history 记录不够用,那就默默地失败呗
router.go(-
100)
router.go(
100)
3、 命名路由
命名路由使用的是:(注意:前面要记得加上一个:)
<li><router-link :to="{ name: 'nameRoute'}">命名路由</router-link></li>
<li><router-link :to="{ name: 'namerouterone', params: { id: 123 }}">命名路由代参</router-link></li>
4、 命名视图:
{ path: '/nameview/child', components: { default: nameviewone, a: nameviewtwo, b: nameviewthree } }
5、 重定向
将一个页面重定向到另一个页面上
比如:https://github.com/vuejs/vue-router/blob/next/examples/redirect/app.js
重定向也是通过 routes
配置来完成,下面例子是从 /a
重定向到 /b
:
const router = new VueRouter({ routes: [ { path: '/a', redirect: '/b' } ] })
重定向的目标也可以是一个命名的路由:
const router = new VueRouter({ routes: [ { path: '/a', redirect: { name: 'foo' }} ] })
甚至是一个方法,动态返回重定向目标:
const router = new VueRouter({ routes: [{ path: '/a', redirect: to => { // 方法接收 目标路由 作为参数 // return 重定向的 字符串路径/路径对象 const { hash, params, query } = to if(query.to === 'foo') { return { path: '/foo', query: null } } if(hash === '#baz') { return { name: 'baz', hash: '' } } if(params.id) { return '/with-params/:id' } else { return '/bar' } } }] })
6、 别名
是可以将一个页面的path名字,改成当前的。
比如:
这里将路径为”/foo”的component改为alias的,原本的就被替换掉了
{ path: '/alias', component: "alias", alias: "/foo" },
更多笔记,待更新~