Vue3知识结构之路由Vue-Router
文章目录
一、Router配置
1. npm install vue-router@4
2.在src文件夹下面创建router文件夹并添加js文件用来声明配置路由
import { createRouter, createWebHashHistory } from "vue-router";
const routerHistory = createWebHashHistory();
const jsonArrayRoute = [
{
path: '/Directive',
component: () => import('@/views/Directive.vue')
},
]
const router = createRouter({
history: routerHistory,
routes: jsonArrayRoute,
})
//export default router
export { router }
3. 在main.js文件进行生效
import { router } from './router/index.js'
const AppNew = createApp(App);
AppNew.use(router);
二、路由嵌套
在路由配置文件里 如下
const jsonArrayRoute = [
{
name: 'KeepAlive',
path: '/KeepAlive',
component: () => import('@/views/API/KeepAlive.vue'),
children: [
{
path: 'image',
component: () => import('@/components/partiesView/image.vue'),
},
}
]
vue3 新语法
<router-view v-slot="{Component}">
<component :is="Component"></component>
</router-view>
三、编程式路由
一、声明式: 以标签形式出现 通过框架提供的组件实现
《a href=‘/path.html’》《/a》
《router-link to=‘/path’》《/router-link》
二、编程式 : 以Script形式出现 通过框架提供的API实现
window.location.href=‘/path.html’
当前vue实例.$router.push({path:‘xxx’})
vue Router传值方式:1.query传值 2.params传值
编程式路由
import { getCurrentInstance } from 'vue';
const {proxy} =getCurrentInstance();//当前vue实例
function toRoute(){
proxy.$router.push({path:'logo'});
proxy.$router.push({name:'logo'}); //路由跳转
proxy.$router.push({name:'logo',query:{wd:'1'}})//路由传值
}
编程式路由传值的接收
import { getCurrentInstance } from 'vue';
const {proxy} =getCurrentInstance();
let routeRecive=proxy.$route.query.wd;
四、动态路由
1.添加路由
proxy.$router.addRoute({
name:'news',
path: '/news',
component: () => import('@/components/routerParties/news.vue'),
});
proxy.$router.push({name:'news'});
2.删除路由
proxy.$router.removeRoute('news');
当在一个button 中的click事件的函数逻辑中通过addRoute新增一个路由配置,然后通过编程式路由跳转到该路由配置的path,成功跳转后刷新页面不能正常显示该组件
五、导航守卫 Navigation Guards
1.全局守卫
全局前置守卫 beforeEach
通常写在main.js或者router配置文件中
router.beforeEach((to, from, next) => {
if (to.meta.isAuth) {
if (confirm('是否进入' + to.name)) {
next();
} else {
alert('已取消访问')
}
} else {
next();
}
})
全局后置守卫 afterEach
router.afterEach((to, from) => {})
2.独享守卫
独享守卫 beforeEnter
写在单个router配置里
const jsonArrayRoute = [
{
path: '/intro',
component: () => import('@/views/intro.vue'),
meta: { isAuth: false },
beforeEnter: (to, from, next) => {
if (to.meta.isAuth == false) {
console.log(to.meta.isAuth);
confirm('是否进入' + to.path);
}
next();
}}];
3.组件内的守卫
beforeRouteEnter / beforeRouteLeave / beforeRouteUpdate
写在单个组件内
beforeRouteEnter(to,from,next){
if (to.meta.isAuth == false) {
console.log(to.meta.isAuth);
if(confirm('是否进入' + to.path)){
next();
}
else{
alert('访问已取消');
}
}else{
next();
}
},
beforeRouteLeave(to,from,next){
// confirm('是否离开' + from.path);
next();
}