路由
1、脚手架生成框架
//index.js
import { createRouter, createWebHashHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
const routes = [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
component: () => import('../views/AboutView.vue')
}
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
export default router
// main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
createApp(App).use(store).use(router).mount('#app')
2、路由跳转传参
- 查询参数传参(分query和path)
- 动态路由传参
2.1、查询参数传参(query和path)
1、query用path编写传参地址,而params用name编写传参地址; 2、query刷新页面时参数不会消失,而params刷新页面时参数会消失; 3、query传的参数会显示在url地址栏中,而params传参不会显示在地址栏中。
// 发送
this.$router.push({
name: 'home',
query: {
id: 'xxx',
title: '123'
}
})
// 接受
console.log(this.$route.query)
//注意:跳转用this.$router,接受用this.$route
2.2、动态路由传参
// 路由界面
{
path: '/about/:name?',
name: 'about',
component: () => import('../views/AboutView.vue')
}
// 访问路径
http://localhost:8080/#/about/jwl/it
// 接受
console.log(this.$route.params)
3、路由嵌套
// router.js
{
path: '/about',
name: 'about',
component: () => import('../views/AboutView.vue'),
children: [
{
path: 'about1',
name: 'about1', //二级路由前面不要带斜杠 /
component: () => import('../views/AboutViewson.vue'),
}
]
}
// AboutView.vue
<router-view></router-view>
// 访问
http://localhost:8080/#/about/about1
3、路由守卫
- 全局守卫
- 独享守卫
- 组件内守卫
全局守卫
router.beforeEach((to,from,next)=>{
console.log('beforeEach',to.from);
if(to.meta.isAuth){//判断当前路由是否需要进行权限控制
if(localStorage.getItem('school')==='daxue'){//权限控制的具体规则
next()
}else{
alert('学校不对,暂无权限查看')
}
}else{
next()//放行
}
})
独享路由守卫
chidren:[
{
path:'news'
component:News,
beforeEnter((to,from,next)=>{
console.log('beforeEnter',to.from);
if(to.meta.isAuth){//判断当前路由是否需要进行权限控制
if(localStorage.getItem('school')==='daxue'){//权限控制的具体规则
next()
}else{
alert('学校不对,暂无权限查看')
}
}else{
next()//放行
}
})
},
]
组件内守卫(在对应的.vue文件配置):
//进入守卫:通过路由规则,进入该组件时被调用
beforeRouteEnter(to,from,next){
if(to.meta.isAuth){//判断当前路由是否需要进行权限控制
if(localStorage.getItem('school')==='daxue'){//权限控制的具体规则
next()
}else{
alert('学校不对,暂无权限查看')
}
}else{
next()//放行
}
}
//进入守卫:通过路由规则,离开该组件时被调用
beforeRouteleave(to,from,next){
console.log('beforeRouteleave');
next();
}