我想将路线添加到vuex的商店中,但失败了。
我使用 initMenu 方法添加路由,在添加之前,我使用 fotmatRoutes 对其进行格式化。
这是 initMenu 代码
export const initMenu = (router, store) => {
//store: vuex
if(store.state.routes.length > 0) {
return;
}
//getRequest: My axios method, codes is under this codes bl
getRequest("/system/config/menu").then(data=>{
if(data){
//formatRoutes: A method to format routes, codes is under getRequest codes block
let fmtRoutes = formatRoutes(data);//Routes array that is going to be added
router.addRoutes(fmtRoutes);
console.log("===================");
console.log("Waiting to add:");
console.log(fmtRoutes);
store.commit('initRoutes', fmtRoutes);
console.log("Added:");
console.log(store.state.routes);
}
})}
getRequest方法代码:
export const getRequest = (url, params) => {
return axios({
method: 'get',
url: `${base}${url}`,
data: params
})};
formatRoutes方法代码:
export const formatRoutes = (routes) => {
let fmRoutes = [];
routes.forEach(route => {
let{
path,
component,
name,
meta,
iconCls,
children
} = route;
if(children && children instanceof Array){
children = formatRoutes(children);
}
let fmRouter={
path: path,
name: name,
iconCls: iconCls,
meta: meta,
children: children,
component (resolve){
if(component.startWith("Home")){
require(['../views/'+component+'.vue'], resolve);
} else if(component.startWith("Emp")) {
require(['../views/emp/'+component+'.vue'], resolve);
} else if(component.startWith("Per")) {
require(['../views/per/'+component+'.vue'], resolve);
} else if(component.startWith("Sal")) {
require(['../views/sal/'+component+'.vue'], resolve);
} else if(component.startWith("Sta")) {
require(['../views/sta/'+component+'.vue'], resolve);
} else if(component.startWith("Sys")) {
require(['../views/sys/'+component+'.vue'], resolve);
}
}
}
fmRoutes.push(fmRouter);
});
return fmRoutes;
}
这是我的控制台日志(对不起,我不知道如何插入图片)
Waiting to add:
Array(5) [ {…}, {…}, {…}, {…}, {…} ]
Added:
Array []
为什么我已提交 fmtRoutes ,但是控制台日志显示 store.state.routes 仍然为空?
补充 :代码包括商店index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
routes:[]
},
mutations: {
initRoutes(state, data) {
this.routes = data;
}
},
actions: {
},
modules: {
}
})