安装:
npm install vue-router -S
配置:
在src目录下创建 router文件夹 创建index.js 做为路由模块 配置index.js
标签 :
用于 显示 组件的位置,类似于插槽
占位符:
<router-view></router-view>
链接符:
<router-link to="/ming"></router-link>
在index.js 中声明路由规则 :
静态路由规则:
path: url 的路径, component: 显示的组件
import Home from "./Home.vue"
routes:[{
//重定向的路由规则
{ path: '/', redirect: '/home' },
// 路由规则
{ path: '/home', component: Home,
子路由规则
children: [
// 默认子路由规则
{ path: '', component: Tab1 },
{ path: 'tab2', component: Tab2 }
]},
}]
例子: 127.0.0.1/ 显示 Home + Tab1
127.0.0.1/tabs2 显示 Home + Tab2
动态路由规则:
this.$route 是路由的"参数对象"
this.$router 是路由的"导航对象"
1. {{ this.$route.params.mid }}
2. { path: '/movie/:mid', component: Movie ,(props: true)}
// 传出参数mid 在组件中用 props:[] 数据接收
3. <router-link to="/movie/1">雷神</router-link>
<router-link to="/movie/2">复联</router-link>
导航
声明式导航:
<router-link></router-link>
编程导航:
1) this.$router.push('hash地址)
跳转到指定hash地址,并且增加历史记录
2) this.$router.replace('hash地址)
跳转到指定hash地址,并且替换掉历史记录
3) this.$router.go(数值 n)
可以在浏览历史中前进或者后退
(如果后退数大于历史数,则停止不动)
简化: $router.back() 后退
$router.forward()前进
导航守卫: 控制路由的访问权限
全局前置守卫:
router.beforeEach(fn(to,from,next) {})
next() 表示放行
next('/hash地址) 强制跳转
next(false) 不允许跳转
// 设置前置守卫
router.beforeEach(function(to, from, next) {
// if (to.path === '/home') {
if (pathArr.indexOf(to.path) !== -1) {
const token = localStorage.getItem('token')
if (token) {
next()
} else {
next('/login')
}
} else {
next()
}
})