不同的历史记录模式
Hash 模式用的是 createWebHashHistory(),不会发送请求到服务器,页面不会刷新,提高性能
import { createRouter, createWebHashHistory } from 'vue-router'
const router = createRouter({
// hash 模式
history: createWebHashHistory(),
routes, // 'routes: routes' 的缩写
})
HTML5模式用的是 createWebHistory()
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
//history模式
history:createWebHistory(),
routes, // 'routes: routes' 的缩写
})
两种模式的区别就在于页面的URL中有无“#”
路由守卫
to,跳转后的页面
from,跳转前的页面
全局守卫
作用于页面全部路由
router.beforeEach((to,from,next)=>{
console.log(to);
console.log(from);
next()//通行证
})
每路守卫(路由独享)
控制一个路由
{
path: '/about',
component: About,
//每路守卫(路由独享)
beforeEnter: (to, from,next) => {//token
console.log(to);
console.log(from);
if(123 == 123){
next()
}
}
},
组件内的守卫
<script>
export default {
data() {
return {
age: 18
}
},
beforeRouteEnter(to, from, next) {//拿不到实例对象,通过next回调函数获取
console.log(to);
console.log(from);
next((vm) => {
console.log(vm.age);
})
console.log("路由进去组件之前");
},
beforeRouteUpdate() {
console.log("路由更新组件之前");
},
beforeRouteLeave() {
console.log("路由离开组件之前");
},
}
</script>
路由懒加载
使用时才会加载,不会和静态导入一样主动加载全部,相比静态导入,速度会更加快。
//静态导入
// import Home from '../views/Home.vue'
//路由懒加载,用到的时候再加载
const Home=()=>import('../views/Home.vue')