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,注意:每次刷新页面后,会重新初始化掉。
本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!