说明:addroutes是用来动态添加路由的,在做权限管理的时候会用到这个api,接下来我们一起来探究一下这个api吧。

一.addroutes的使用

1.router/index.js

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
]

export const asyncroutes = [
  {
    path: '/jiagou',
    name: 'jiagou',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ '../views/jiagou.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

2.store/index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    isLogin: false
  },
  mutations: {
    login (state) {
      state.isLogin = true
    }
  },
  actions: {},
  modules: {}
})

3.home.vue

<template>
  <div class="">
    <button @click="fn">登录页</button>
    <router-view />
  </div>
</template>

<script>
import { asyncroutes } from '../router/index'
export default {
  name: '',
  methods: {
    fn () {
      // console.log(this.$router)
      // this.$router.addRoutes(asyncroutes)
      this.$store.commit('login')
      console.log(this.$router)
      this.$router.addRoutes(asyncroutes)
    }
  }
}
</script>

<style scoped></style>

4.App.vue

<template>
  <div id="app">
    <div id="nav">
      <router-link to="/">登录</router-link> |
      <router-link to="/about">首页</router-link>
      <div v-if="$store.state.isLogin">
        <router-link to="/jiagou">架构</router-link>
      </div>
    </div>
    <router-view />
  </div>
</template>

<style lang="less">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

#nav {
  padding: 30px;
  display: flex;
  justify-content: center;

  a {
    font-weight: bold;
    color: #2c3e50;

    &.router-link-exact-active {
      color: #42b983;
    }
  }
}
</style>

目前展示的页面:

 当前只能访问到这两个路由的界面,接下来,我们通过addroutes这个api来添加一个可以访问的页面。

点击登录页时

可以看出多了一个跳转的页面,这个页面就是通过addroutes这个api动态添加的。 

Logo

前往低代码交流专区

更多推荐