版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Zckguiying/article/details/85871687
import()动态加载相关资料:https://blog.csdn.net/Zckguiying/article/details/85864233
需求描述:前端项目中必定要有本地数据mock的模块,实现前后端分离,解决开发时因前后端接口的依赖而导致开发效率低下的问题。
实现方案:这里主要使用了es6 import()动态加载模块来实现mock功能。
1、准备需要mock的json数据,命名为getLabelDetail.js;
注意:这里的文件名与接口地址路由的最后一层保持一致,测试接口地址为'/reference/label/getLabelDetail',故命名getLabelDetail.js。
getLabelDetail.js
export default {
'code': '200',
'msg': '',
'result': {
'labelId': '12332131231213341',
'labelName': '上海中心大厦',
'labelAttribute': {
'city': '上海'
}
}
}
2、根据接口地址找到对应文件,动态加载相应的json数据。
mockApi.js
/**
* 获取mock的json数据
* @param uri 接口地址
* @param params请求参数
* @returns {Promise<any>}
*/
function getMockJson(uri, params) {
console.log(`接口地址:${uri}---请求参数:`, params)
let fileName = uri.substring(uri.lastIndexOf('/') + 1)
return new Promise((resolve, reject) => {
// 这里使用import()动态加载,路劲为相对路径
import(`../../mock/${fileName}.js`).then(({default: res}) => {
if (res.code === '200' || res.code === 200) {
resolve(res.result)
} else {
reject('mock数据中code非200,请检查!')
}
}).catch(error => {
console.error(error)
})
})
}
// 获取标签详细信息
export function getLabelDetail(params) {
let uri = '/reference/label/getLabelDetail'
return getMockJson(uri, params)
}
3、页面中使用
import { getLabelDetail } from '@/services/mockApi'
// ...
getLabelDetail({appId: 123, labelId: 123123}).then(res => {
console.log('结果', res)
// ...
})