通过addroutes动态添加路由

说明: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动态添加的。 

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值