1 什么是动态路由:

工作中经常用到的情况就是,在导航菜单中,如果没有登录,我们则只展示一部分信息,如果登录,再将其余的信息展示,这就是动态路由,此时我们不需要在手动配置路由,后端将路由数据返回,我们拿到数据,进行匹配。

2 效果图:

登录前:

登录后:

3 完整代码部分:

(1)这里直接在根组件测试 app.vue 文件

<template>
  <div id="app">
    <div class="nav">
      <div class="navBar">
        <template v-for="(item, index) in updateNav">
          <li :key="index" v-if="!item.meta.hidden">
            <router-link :to="item.path">{{ item.meta.title }}</router-link>
          </li>
        </template>
      </div>
      <div class="login">
        <div>
          <el-button size="small" type="primary" @click="login">
            登录</el-button
          >
        </div>
        <div>
          <el-button size="small" type="danger" @click="loginOut">
            退出</el-button
          >
        </div>
      </div>
    </div>

    <div class="container">
      <router-view></router-view>
    </div>
  </div>
</template>

<script>
// 加载动态路由
import useaddRoute from "./utils/loadingRouter";
import { mapGetters } from "vuex";
export default {
  name: "App",
  components: {},
  data() {
    return {

    };
  },
  created() {
    useaddRoute();
  },
  mounted() {},

  computed: {
    ...mapGetters(["updateNav", "updateStore"]),
  },

  methods: {
    // 登录
    login() {
      this.$confirm("确认登录?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log(this.updateStore);
          if (!this.updateStore) {
            // 触发登录 更改状态
            this.$store.dispatch("updateStoreChange", true);
            console.log(this.updateStore);
            useaddRoute();
            this.$message({
              type: "success",
              message: "登录成功!",
            });
          } else {
            this.$message({
              type: "error",
              message: "您已登录!!!",
            });
            return;
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消登录",
          });
        });
    },
    // 退出
    loginOut() {
      this.$confirm("将要退出登录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "退出成功!",
          });
          this.$store.dispatch("updateStoreChange", false);
          this.isLogin ? "" : location.reload();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消退出",
          });
        });
    },
  },
};
</script>

<style lang="scss">
.nav {
  padding: 10px 0;
  background-color: #545c64;
  display: flex;
  justify-content: space-between;
  .navBar {
    width: 800px;
    display: flex;
    li {
      width: 60px;
      color: #fff;
      text-align: center;
      font-size: 16px;
      line-height: 32px;
      margin-left: 30px;
    }
  }
  .login {
    width: 150px;
    display: flex;
    justify-content: space-around;
  }
}
.container {
  margin-top: 20px;
  width: 700px;
  height: 400px;
  border: 10px solid #f0f5ff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
  display: flex;
  justify-content: center;
  align-content: center;
}
</style>

(2)main.js 文件

import Vue from 'vue'
import App from './App.vue'
import router from './router/index.js'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

import store from './store/index.js'

import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);

Vue.config.productionTip = false

new Vue({
  el:'#app',
  router,
  store,
  render: h => h(App),
})

(3)router.js文件


import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter)

// 引入静态路由
import { staticRouter } from "@/utils/data";
const routes = staticRouter;

const router = new VueRouter({
    routes
})

export default router

(4)模拟数据以及动态追加路由的方法

data.js 模拟数据

// 静态路由
export const staticRouter = [
    {
        path:'/',
        component:() => import('../views/staticRoutes/static1.vue'),
        meta: { title: '静态1'}
    },
    {
        path:'/2',
        component:() => import('../views/staticRoutes/static2.vue'),
        meta: { title: '静态2'}
    },
    {
        path:'/3',
        component:() => import('../views/staticRoutes/static3.vue'),
        meta: { title: '静态3'}
    },
    {
        path:'*',
        component:() => import('../views/staticRoutes/static1.vue'),
        meta: { title: '错误404',hidden:true}
    }
]


// 动态路由
export const dynamicRouter = [
    {
        path: '/d1',
        component: 'dynamicRoutes/dynamic1.vue',
        meta: { title:'动态1'}
    },
    {
        path: '/d2',
        component: 'dynamicRoutes/dynamic2.vue',
        meta: { title:'动态2'}
    },
    {
        path: '/d3',
        component: 'dynamicRoutes/dynamic3.vue',
        meta: { title:'动态3'}
    }
]

loadingRouter.js 追加路由

import { staticRouter, dynamicRouter } from "./data";
import router from "../router/index";
import store from "../store/index";

const routes = staticRouter;

export default function useaddRoute() {
    if (store.state.app.isLogin) {
        // 模拟发送请求 放回后端路由数据 
        setTimeout(() => {
            let data = routesData(dynamicRouter)
            store.dispatch('Nav', data)
            // 循环添加  addRoute (vue-router 建议使用的方法)
            data.forEach(item => {
                router.addRoute(item)
            });
        }, 2000);
    } else {
        store.dispatch('Nav', staticRouter)
    }


}

// 追加动态路由
function routesData(result) {
    result.forEach(item => {
        routes.push({
            path: item.path,
            name: item.name,
            meta: item.meta,
            // 注意追加路径
            // component: () => import(`../views/dynamicRoutes/`),
            component: () => import(`../views//${item.component}`),
        })
    })
    return routes
}

(5)vuex

index.js 

import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
import app from './module/app'

Vue.use(Vuex)

const store = new Vuex.Store({
  modules: {
    app,
  },
  getters
})

export default store

getters.js

const getters = {
    updateStore: state => state.app.isLogin,
    updateNav: state => state.app.routeArr,
  }
export default getters

 module文件下的 app.js

const state = {

    isLogin:false,
    routeArr:[],   
}

// mutations操作数据
const mutations = {

    CHANGESTORE(state,data){
        state.isLogin = data;
    },

    HEARDER(state,data){
        state.routeArr = data;
    }
  
}

const actions = {

    updateStoreChange(contenxt,state){
        contenxt.commit('CHANGESTORE',state)
    },

    Nav({commit},state){
        commit('HEARDER',state)
    }
}

// 导出
export default {
  state,
  mutations,
  actions
}

Logo

前往低代码交流专区

更多推荐