天天看點

【Vue】通過“全局路由守衛”實作路由元件”切換“時的”權限控制“

一、【全局】路由元件“切換”前設定“權限控制”

注意:全局就是對【所有】路由元件切換時的權限控制,隻要元件切換,就會調用此事件。

1、在app.vue中設定一下全局變量username,以友善判斷

【Vue】通過“全局路由守衛”實作路由元件”切換“時的”權限控制“

在index.js路由元件中設定

【Vue】通過“全局路由守衛”實作路由元件”切換“時的”權限控制“

【前置 - 切換打開前】在index.js路由配置中增加beforeEach

【Vue】通過“全局路由守衛”實作路由元件”切換“時的”權限控制“

 【後置 - 切換打開後】在index.js路由配置中增加afterEach 

【Vue】通過“全局路由守衛”實作路由元件”切換“時的”權限控制“

 App.vue

<template>
  <div id="myapp">
    <!-- 第1行 -->

    <div class="left">
      <!-- 路由跳轉連結 -->
      <router-link class="box_1" to="/Box_1" active-class="active">
        Box1元件>
      </router-link>
      <!-- 路由跳轉連結 -->
      <router-link class="box_2" to="/Box_2" active-class="active">
        Box2元件>
      </router-link>
    </div>
    <div class="right">
      <!-- 顯示路由元件 -->
      <router-view> </router-view>
    </div>
  </div>
</template>

<script>      

2、index.js中增加路由守衛,設定路由切換事件

index.js

// 引入路由
// eslint-disable-next-line no-unused-vars
import Vue from 'vue'
import VueRouter from 'vue-router'
import Box_1 from '../pages/Box_1.vue'
import Box_2 from '../pages/Box_2.vue'
import Menu_1 from '../pages/Menu_1.vue'
import Menu_2 from '../pages/Menu_2.vue'

Vue.use(VueRouter)
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}


// 建立一個路由器

const mRouter = new VueRouter({
    routes: [

        {
            path: '/Box_1',
            component: Box_1,
            meta: { isAuth: false, title: "盒子1" },  // 通過meta設定目前元件不需要false權限判斷
            children: [
                {
                    name: 'myMenu',  // 用name代替路徑
                    path: 'Menu_1',
                    component: Menu_1,
                    props($route) {
                        return {
                            id: $route.params.id,
                            name: $route.params.name,
                        }
                    }
                },
                {
                    path: 'Menu_2',
                    component: Menu_2
                },
            ]
        },
        {
            path: '/Box_2',
            component: Box_2,
            meta: { isAuth: true, title: "盒子2" },  // 通過meta設定目前元件需要true權限判斷
            children: [
                {
                    path: 'Menu_1',
                    component: Menu_1
                },
                {
                    path: 'Menu_2',
                    component: Menu_2
                },

            ]
        },
    ]


})


// 【前置】路由守衛————初始化的時候被調用、每次路由切換之前被調用

mRouter.beforeEach((to, from, next) => {

    console.log("====【前置】====");
    console.log(to, from);

    // 判斷使用者名username=csj,就執行切換路由元件頁面
    // 所有設定this.meta.isAuth === true的路由元件執行檢查權限

    if (to.meta.isAuth === true) {
        if (localStorage.getItem('username') === 'csj') {
            next()

        }
    } else {
        alert("無權檢視")
    }
})

// 【後置】路由守衛————初始化的時候被調用、路由切換進入後被調用

mRouter.afterEach((to, from) => {
    console.log("====【後置】====");
    console.log(to, from);
    document.title = to.meta.title   // 把網頁标題改為路由元件設定的标題 meta: { isAuth: false, title: "盒子1" }
})



export default mRouter      

二、【獨享守衛】路由元件“切換”前設定“權限控制”

index.js

【Vue】通過“全局路由守衛”實作路由元件”切換“時的”權限控制“

 Menu_1.vue

<template>
  <div class="m_box">
    {{ id }}.{{ name }}
    <br />
    <input type="text" />
  </div>
</template>

<script>
export default {
  name: "Menu_1",
  props: ["id", "name"],
  mounted() {
    console.log("=============");
    console.log(this);
  },
  activated() {
    // alert("進來了");
  },

  deactivated() {
    // alert("離開了");
  },

  // 通過路由規則,【進入】該元件時被調用

  beforeRouteEnter(to, from, next) {
    console.log("進入了menu_1.vue元件!");

    // 判斷使用者名username=csj,就執行切換路由元件頁面
    // 所有設定this.meta.isAuth === true的路由元件執行檢查權限

    if (to.meta.isAuth === true) {
      if (localStorage.getItem("username") === "csj") {
        next();
      }
    } else {
      alert("無權檢視11");
    }
  },

  // 通過路由規則,【離開】該元件時被調用
  beforeRouteLeave(to, from,next) {
    console.log("離開了menu_1.vue元件!", to, from);
    next();
  },
};
</script>

<style scoped>
.m_box {
  width: 95%;
  height: 68px;
  border: 1px rgb(253, 211, 211) solid;
  margin-top: 5px;
  text-align: center;
  line-height: 28px;
  overflow: hidden;
  background-color: rgb(248, 248, 248);
}
</style>      

繼續閱讀