vue 动态添加路由

最近在研究权限的相关东西,自然动态加载路由信息少不了。接下来我就来专门记录下我研究的东西。

1、首先后端代码返回一个对象,用java写的,返回的是对象,不是字符,如果是字符前端注意转换成对象。

@GetMapping("/home/index")
public List<Router> index() {
    List<Router> routers = new ArrayList<>();
    Router router = new Router();
    router.setPath("/index");
    router.setName("index");
    router.setComponent("components/index");
    routers.add(router);
    return routers;
}

2、随便找个组件,在里面动态添加路由信息。我这里用到vuex相关东西,不多介绍这个了。注意:在import的时候,一定不能全部使用变量,的有一部分路径信息才行,我这里是@/表示根目录,如果只写变量是读取不到模块的。

<template>
  <div>测试下router</div>
</template>

<script>
import axios from 'axios'
export default {
  data () {
    return {
      aa: []
    }
  },
  created () {
    // 创建一个请求
    axios.get('http://localhost:8080/home/index').then(response => {
      var routers = []
      response.data.forEach(item => {
        var com = item.component
        var temp = {
          path: item.path,
          name: item.name,
          component: () => import(`@/${com}`)
        }
        routers.push(temp)
        this.$store.commit('SET_ROUTEINFO', routers)
      })
      console.dir(this.$store.getters.routeInfo)
      this.$router.addRoutes(this.$store.getters.routeInfo)
    }).catch(error => console.dir(error))
  }
}
</script>

3、然后你就可以访问http://localhost/#/index,注意:每次刷新页面后,会重新初始化掉。

 

 

转载于:https://my.oschina.net/uwith/blog/3039148

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值