以接口/sys/menu/nav导航菜单(按权限过滤)为例
涉及到的文件有
config/api.js
fetch/menu-api.js
store/modules/menu.js
store/index.js
menu/index.vue具体调用页面
1、config/api.js中配置接口定义
同模块的接口放到一个对象中,此处为MenuApi
1 2 3 | export const MenuApi = { nav: '/sys/menu/nav', // 导航 } |
2、fetch/menu-api.js中封装同步接口调用对象,对外暴露接口参数
1 2 3 4 5 6 7 8 9 10 11 12 | import BaseApi from '@/config/baseapi' class Menu extends BaseApi { constructor() { super('MenuApi') } // 导航 async nav(obj) { return await this.get(this.MenuApi.nav, obj) } } export default new Menu() |
3、纳入store管理,store按模块区分不同接口,新增store/modules/menu.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import menuFetch from '@/fetch/menu-api.js' export default { namespaced: true, state: () => { return { menus: '' } }, mutations: { SET_MENUS: (state, menus) => { state.menus = menus } }, actions: { // 导航 async nav({ commit }, obj) { const data = await menuFetch.nav(obj) return data } } } |
4、store/index.js引入store模块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import Vue from 'vue' import Vuex from 'vuex' import getters from './getters' import menu from './modules/menu' Vue.use(Vuex) const store = new Vuex.Store({ modules: { app, settings, user, role, menu }, getters }) export default store |
5、具体页面调用,通过vuex进行接口调用
片段一:script下引用vuex,并建立接口常亮
1 2 3 | <script> import vuex from 'vuex' const menu = vuex.createNamespacedHelpers('menu') |
片段二:methods方法中引入要调用的方法
1 2 | methods: { ...menu.mapActions(['getMenuList', 'menuListAll', 'saveMenu', 'menuInfo', 'updateMenu', 'deleteMenu']), |