Compare commits

..

1 Commits

Author SHA1 Message Date
httpxuchao
dc3b7a5250 导航守卫 2022-03-09 18:55:08 +08:00
5 changed files with 84 additions and 6 deletions

View File

@ -7,6 +7,9 @@ import 'element-ui/lib/theme-chalk/index.css';
const routes = [
{
path:"/",
meta: {
roles: 1
},
component: ()=>import("./pages/nav.vue"),
// 以上两行 代表着项目的根路径就代表着默认打开nav 页面
@ -14,15 +17,36 @@ const routes = [
children: [{
path:"user",
component: ()=>import("./pages/user.vue")
meta: {
roles: 1
},
component: ()=>import("./pages/user.vue"),
beforeEnter: (to,from,next) => {
console.log("路由独享守卫user")
next()
}
},
{
path:"index",
component: ()=>import("./pages/index.vue")
meta: {
roles: 1
},
component: ()=>import("./pages/index.vue"),
beforeEnter: (to,from,next) => {
console.log("路由独享守卫index")
next()
}
},
{
path:"login",
component: ()=>import("./pages/login.vue")
meta: {
roles: 2
},
component: ()=>import("./pages/login.vue"),
beforeEnter: (to,from,next) => {
console.log("路由独享守卫login")
next()
}
}
// 上面这种路径的写法是绝对路径 前面对应的是@click="$router.push('/index')和@click="$router.push('/user')
// 但是一般都是用相对路径
@ -37,24 +61,54 @@ Vue.use(ElementUI);
Vue.use(Router)
const router = new Router({
mode: "history", // history模式 打开网页的时候地址不带有#
// vue2 默认是hash模式
routes // 缩写相当于routes: routes
})
// const shenfen = "user"
// 自动被执行 页面跳转的时候
router.beforeEach((to, from, next) => {
console.log(to); //到哪里去
console.log(from); //从哪里来
console.log("这是导航守卫");
if(to.path != "/nav") {
if(to.meta.roles == 1) {
console.log("执行next")
next() // 控制页面跳转
}else {
//alert("抱歉,您没有此权限!")
alert("抱歉,您没有此权限!将返回首页!")
// 跳转页面
// console.log(from);
router.push("/index")
// next()
//next("/index") 等同于 router.push("/index")
// next("/index") //一般用next的话控制台会出现错误,但不影响效果
}
// 前置导航守卫
// console.log("前置导航守卫")
// next()
})
// 全局解析守卫
router.beforeResolve((to, from, next) => {
console.log("全局解析守卫")
next()
})
// 全局后置钩子
// 注意没有参数next,只有to,from
router.afterEach(() => {
// console.log(to,from)
// 若是加上上面这句话,需要加上参数,即 router.afterEach((to,from) => {...})
console.log("跳转成功")
})
Vue.config.productionTip = false
new Vue({

View File

@ -10,6 +10,10 @@
<script>
export default {
name: "PageIndex",
beforeRouteEnter(to,from,next) {
console.log("组件渲染index")
next()
},
data() {
return {
user1: "",

View File

@ -6,7 +6,11 @@
<script>
export default {
name:"PageLogin"
name:"PageLogin",
beforeRouteEnter(to,from,next) {
console.log("组件渲染login")
next()
}
}
</script>

View File

@ -68,6 +68,18 @@ export default {
}
},
beforeRouteEnter(to,from,next) {
console.log("组件渲染nav")
next()
},
beforeRouteUpdate(to,from,next) {
console.log("组件复用nav")
next()
},
beforeRouteLeave(to,from,next) {
console.log("nav组件离开")
next()
}
};
</script>

View File

@ -9,6 +9,10 @@
<script>
export default {
name:"PageUser",
beforeRouteEnter(to,from,next) {
console.log("组件渲染user")
next()
},
methods: {
back() {
this.$router.go(-1)