zoukankan      html  css  js  c++  java
  • $router.addRoutes()+vuex 动态添加路由

    1、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
        }
      }
    })

    2、views/Login.vue:

    <template>
      <div>
        <h1>登录页面</h1>
        <button @click="handleClick">按钮</button>
      </div>
    </template>
    <script>
    import { asyncRoutes } from '../router'
    export default {
      methods: {
        handleClick() {
          this.$store.commit('login')
          this.$router.addRoutes(asyncRoutes) // 将asyncRoutes中的路由添加到路由表中
        }
      }
    }
    </script>

    views/Register:

    <template>
      <div>
        <h1>注册页面</h1>
      </div>
    </template>

    views/About.vue:

    <template>
      <div>
        <h1>关于页面</h1>
      </div>
    </template>

    3、router.js:

    import Vue from 'vue'
    import VueRouter from 'vue-router'
    
    Vue.use(VueRouter)
    
    import Login from '@/views/Login'
    import Register from '@/views/Register'
    import About from '@/views/About'
    const routes = [
      { path: '/login', component: Login },
      { path: '/register', component: Register }
    ]
    
    // 带权限的路由
    export const asyncRoutes = [{ path: '/about', component: About }]
    
    const router = new VueRouter({
      mode: 'history',
      routes
    })
    
    export default router

    4、App.vue:

    <template>
      <div id="app">
        <div class="router">
          <router-link tag='div' class="nav-link" to="/login">登录</router-link>
          <router-link tag='div' class="nav-link" to="/register">注册</router-link>
          <router-link tag='div' class="nav-link" to="/about" v-if="$store.state.isLogin">About</router-link>
        </div>
        <h1>动态添加路由</h1>
        <router-view></router-view>
      </div>
    </template>
    <style lang="less" scoped>
    #app {
      text-align: center;
      .router {
        display: flex;
        justify-content: flex-end;
        width: 100%;
        height: 44px;
        background-color: #424242;
      }
      .nav-link {
        width: 100px;
        height: 100%;
        text-align: center;
        line-height: 44px;
        color: #fff;
      }
    }
    </style>

    效果:about路由是权限路由,默认情况下vuex中isLogin为false,此时不展示。当进入到login页面时,点击登录按钮,触发vuex中isLogin为true,此时about路由展示。但此时进入到about中时router-view没有任何内容,需要在点击按钮的同时,将asyncRoutes中的路由(about)添加到路由表中,此时再进入到about路由便可以正常展示about组件

  • 相关阅读:
    CentOS安装gotop
    oracle 非sys用户创建新用户 授权后 plsql看不到视图
    解决Eclipse+ADT连接夜神模拟器失败问题
    Ext JS v2.3.0 Ext.grid.ColumnModel renderer Record 获取列值
    vi常用快捷键汇总
    外键的变种
    完整性约束
    数据类型2
    数据类型
    表的操作
  • 原文地址:https://www.cnblogs.com/wuqilang/p/15120261.html
Copyright © 2011-2022 走看看