vue-router是一个vue插件,用来提供路由功能。通过路由的改变可以动态加载组件,达到开发单页面程序的目的
1.基本使用
1)声明组件
let com1 = {}
let com2 = {}
let com3 = {}
2)声明路由器
let router = new VueRouter({
routes: [
{ path: '/a', component: com1 },
{ path: '/b', component: com2 },
{ path: '/c', component: com3 },
]
})
3)路由注册
let vm = new Vue({
el: '#app',
router: router
})
4)路由使用
<router-link to="/a">A组件</router-link>
<router-link to="/b">B组件</router-link>
<router-link to="/v">C组件</router-link>
// 路由视口,用来加载对应的组件
<router-view></router-view>
2.动态路由
let router = new VueRouter({
routes: [
{ path: '/user/:username/:id', component:com1 }
]
})
<router-link to="/user/zhangsan/1001"></router-link>
获取路由携带参数
let com1 = {
data() {
return {
id: null,
username: null
}
},
template: ``,
created() {
this.id = this.$route.params.id;
this.username = this.$route.params.username;
},
watch() {
$route(to, from) {
this.id = to.params.id;
this.username = to.params.username;
}
}
}
3.路由守卫
1)全局守卫
let router = new VueRouter({
routes: [
{...}
]
})
// 全局前置守卫
router.beforeEach((to, from, next) => {
.......拦截操作
next();
// next(false);
})
// 全局后置守卫
router.afterEach((to, from) => {
.......之后操作
})
2)路由独享守卫
let router = new VueRouter({
routes: [
{
path: '/a',
component: com1,
beforeEnter(to, from, next) {
.......拦截操作
next();
}
}
]
})
3)组件内守卫
let com1 = {
data(){
return {}
},
template: ``,
// 进入当前组件之前拦截
beforeRouteEnter(to, from, next) {
.......拦截操作
next();
},
// 在当前组件中,路由发生改变时触发
beforeRouteUpdate(to, from, next) {
.......拦截操作
next();
},
// 离开当前组件之前,触发
beforeRouteLeave(to, from, next) {
.......拦截操作
next();
}
}
4.嵌套路由
品字形布局
嵌套路由的定义
let router = new VueRouter({
routes: [
{
path: '/student',
component: comStu,
children: [
{ path: 'grade', component: comGrade },
{ path: 'register', component: comRegister },
]
}
]
})
5.编程式导航
this.$router.push() // 在history历史栈中新增一条记录
this.$router.push({ path: '/a' })
this.$router.push({ name: 'comA' })
// 路径跳转和query搭配使用
this.$router.push({ path: '/a', query: { username: 'zhangsan' } })
// 名字跳转和params搭配使用
this.$router.push({ name: 'comA', params: { age: 12 } })
参数获取
在跳转的目标组件中,只要能够访问到$route就能拿到跳转携带的参数
query传参和params传参区别
1.query传参参数保存在url地址栏中,以查询字符串的形式拼接上去
2.安全性来讲,params比较安全,query会显示在地址栏中,容易造成数据泄露
3.刷新页面时,query中的数据不受影响,而params中的数据直接消失
this.$router.replace() // 直接替换当前路由,不会产生新的历史记录
this.$router.go() // 内部接受正值或负值的整数作为参数,正数就是前进,负数就是后退(在历史记录中)
6.路由模式
hash路由和history路由的区别:
1.hash路由在地址栏URL上有#,而history路由没有会好看一点
2.进行回车刷新操作,hash路由会加载到地址栏对应的页面,而history路由一般就404报错了
(刷新是网络请求,没有后端准备时会报错)。
3.hash路由支持低版本的浏览器,而history路由是HTML5新增的API。
4.hash的特点在于它虽然出现在了URL中,但是不包括在http请求中,所以对于后端是没有一点影响的,
所以改变hash不会重新加载页面,所以这也是单页面应用的必备。
5.history运用了浏览器的历史记录栈,之前有back,forward,go方法,之后在HTML5中新增了
pushState()和replaceState()方法(需要特定浏览器的支持),它们提供了对历史记录进行修改的功能,
不过在进行修改时,虽然改变了当前的URL,但是浏览器不会马上向后端发送请求。