文章目录
前言
提示:本文是跟随vue-router官网逐步展开,希望能更深入了解vue-router基础和使用,相关顺序会打乱,请谅解😊
一、安装
- 戳这里下载 / CDN
- NPM
npm install vue-router
在模块化工程中使用
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
二、路由对象
1.定义
一个路由对象 (route object) 表示当前激活的路由的状态信息,包含了当前 URL 解析得到的
信息,还有 URL 匹配到的路由记录 (route records)。
注意点:
- 路由是不可变的,每次成功导航后都会产生一个新的对象
- 路由对象出现在多个地方:
- 组件内,即this.$route
- $route观察者内回调
- router.match(location)的返回值
- 导航守卫的参数
router.beforeEach((to, from, next) => {
// `to` 和 `from` 都是路由对象
})
- scrollBehavior方法的参数
const router = new VueRouter({
scrollBehavior(to, from, savedPosition) {
// `to` 和 `from` 都是路由对象
}
})`
2.路由对象属性
- $route.path:当前路由的路径,总是解析为绝对路径,如
/foo/bar
(string) - $route.params:key/value对象,包含动态片段和全匹配片段,没有则为
{}
- $route.query:key/value对象,表示URl参数,例如:
/foo?user=1
即route.query.user==1
- $route.hash:当前路由的hash值(带#),没有则为空字符串
- $route.fullPath:完成解析后的URl,包含查询参数hash的完整路径
- $route.matched:Array,包含当前路由的所有嵌套的路由记录
- $route.name:当前路由的名称
- $route.redirectedFrom:如果存在重定向,即为重定向来源的路由的名字
//路由记录就是 routes 配置数组中的对象副本 (还有在 children 数组)。
const router = new VueRouter({
routes: [
// 下面的对象就是路由记录
{
path: '/foo',
component: Foo,
children: [
// 这也是个路由记录
{
path: 'bar', component: Bar }
]
}
]
})
当 URL 为 /foo/bar,$route.matched 将会是一个包含从上到下的所有对象 (副本)
ps: hash值如何设置呢?一般在index.js中创建路由时设置
const router = new VueRouter({
mode: 'hash', //设置为hash则路径中会带有#,设置为history则没有
base: process.env.BASE_URL,
routes
})
这里了解到hash是一种url模式,另外一种是history,history模式是需要后台去设置,大家可以去百度帮看看 url hash模式戳这里
三、用法
1.项目初始化–引入
这里说一下,一般项目中都会新建一个router文件夹,下有router.js(包含所有路径配置),然后在main,js中引入
index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
// 主界面/首页
{
path: '/',
name: 'Home',
component: import('../views/Home.vue')
},
// 其他
{
path: '/about',
name: 'About',
component: () => import('../views/About.vue')
},
{
path: '*',
redirect: '/404'
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
// 解决路由点击多次报错,重写路由push
const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
return routerPush.call(this, location).catch(error => error)
}
export default router
main.js
import ro