Vue dynamically add routes

Recently, things related to research authority are naturally 动态加载路由信息indispensable. Next, I will specifically record what I researched.

1. First, the back-end code returns one 对象, written in java, and returns what is 对象not a character. If it is a character, pay attention to convert it to the front end 对象.

@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. Just find a component inside 动态添加路由信息. I use vuexrelated things here , I won't introduce this much. Note: At importthe time, it must not be all 使用变量, and only part of the path information is necessary. In my case, @ / means the root directory. If you only write variables, you cannot read the module.

<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. Then you can visit http: // localhost / # / index, note: every time you refresh the page, it will be re-initialized.

Published 252 original articles · Like 106 · Visits 30,000+

Guess you like

Origin blog.csdn.net/weixin_42554191/article/details/105459926