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