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,注意:每次刷新页面后,会重新初始化掉。

发布了252 篇原创文章 · 获赞 106 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_42554191/article/details/105459926