源码地址: https://gitee.com/hannah_bingo/vue_demo/
vue-router多级路由的使用
- 欢迎star+fork
const router = new VueRouter({
routes: [
{
path: "/about",
component: About,
meta: { title: "关于" },
},
{
path: "/home",
component: Home,
meta: { title: "主页" },
children: [
{
path: "news",
component: News,
meta: { title: "新闻" },
},
{
path: "message",
component: Message,
meta: { title: "消息" },
children: [
{
name: "xiangqing",
path: "detail",
component: Detail,
props($route) {
return { id: $route.query.id, title: $route.query.title };
},
meta: { isAuth: true, title: "详情" },
},
],
},
],
},
],
});
只有相关用法,限制范围并没有起到有效拦截作用
// 全局前置路由守卫--每次路由切换之前,初始化的时候被调用
router.beforeEach((to, from, next) => {
console.log("路由前置守卫", to, from);
if (to.meta.isAuth) {
if (to.path === "/home/message/detail") {
next();
} else {
alert("学校名不对,无权限查看");
}
} else {
next();
}
});
router.afterEach((to, from) => {
console.log("后置路由守卫", to, from);
document.title = to.meta.title || "主页";
});
<template>
<div>
<ul>
<li v-for="m in messageList" :key="m.id">
<router-link
:to="{
path: '/home/message/detail',
query: {
id: m.id,
title: m.title,
},
}"
>{{ m.title }}router-link
>
li>
ul>
<hr />
<router-view> router-view>
div>
template>
<script>
export default {
name: "Message",
data() {
return {
messageList: [
{ id: "001", title: "消息001" },
{ id: "002", title: "消息002" },
{ id: "003", title: "消息003" },
],
};
},
};
script>
<style>style>
<template>
<div>
<li>消息编号:{{$route.query.id}}li>
<li>消息标题:{{$route.query.title}}li>
<li>消息编号:{{$route.params.id}}li>
<li>消息标题:{{$route.params.title}}li>
<li>{{id}}li>
<li>{{title}}li>
div>
template>
<script>
export default {
name: 'Detail',
props:['id','title'],
mounted() {
console.log(this.$route);
}
}
script>
<style>
style>
Gitee地址 vue-router多级路由的使用
详细笔记地址
传递参数
<router-link :to="/home/message/detail?id=666&title=你好">跳转router-link>
<router-link
:to="{
path:'/home/message/detail',
query:{
id:666,
title:'你好'
}
}"
>跳转router-link>
接收参数:
$route.query.id
$route.query.title
作用:对路由进行权限控制
分类:全局守卫、独享守卫、组件内守卫
全局前置守卫:
//全局前置守卫:初始化时执行、每次路由切换前执行
router.beforeEach((to,from,next)=>{
console.log('beforeEach',to,from)
if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制
if(localStorage.getItem('school') === 'atguigu'){ //权限控制的具体规则
next() //放行
}else{
alert('暂无权限查看')
// next({name:'guanyu'})
}
}else{
next() //放行
}
})