封装一个接口方法,根据条件,调用不同接口数据
首先在接口引入文件里配置
import requests from 'utils/request'
封装一个方法类名
// 查询采购场景 没有启用
export const getList = (url,method,data: any) => {
return requests(url, {
method: method,
query: data
});
};
在Vue项目中data函数里、或者react 项目中state里
设置一个初始变量
getListOption: { url; method } = {
url: '/yst-pur/pur/purscene/search', // 初始化想要默认先走的接口
method: 'post'
};
enableFlag: boolean = false; //是否启用 跟后台约定的
sceneIds: string[] = []; //已选中的id数组
假设我们是要创建文件之后就执行加载接口文件进行获取接口赋值展示
在Vue项目中create 或者mounted 钩子函数中,在react项目的 componentDidMount 钩子函数中执行接口的调佣
这里是一react为例,Vue也是一样的,换换钩子函数就可以了。
async componentDidMount() {
this.setDefaultParams(this.props?.match?.params?.id); // 传过来详情id参数,这里接收了一下。
}
setDefaultParams = async (id) => {
const deitem = await service.getProcurementTypeId(id); // 详情接口
// 下面就是判断条件,要执行的是那一条接哭数据
if (deitem && deitem.data.enableFlag) { // 如果启用
this.getListOption = {
url: `/yst-fin/fin/purSettleDef/listScene`, // 查询已对应采购场景--启用之后的
method: 'post'
};
this.enableFlag = true; // enableFlag 是我定义的一个启用状态true或false,跟后台约定的,上边已经有定义了
} else { // 如果不启用
this.enableFlag = false; // 没有启用的状态
this.sceneIds = deitem.data.sceneIds;
}
this.setState({ isInitFinish: true });
};
当我们上边定义类方法的时候,可能接口局不能直接调,要自己去赋值了
所以
request: async (paramData) => {
return service.getList(
this.getListOption.url, // 初始化接口
this.getListOption.method,
{ // 传参
...paramData,
defineId: this.props?.match?.params?.id,
es3: 'NON', // 不免值
size: 100, // 不分页,统一的固定值
orders: [{ asc: false, column: 'createTime' }] //排序
}
);
},
// 当我们执行接口成功之后,走的一个成功防范
successCallBack: (successTableRef) => {
this.setDefaultSelectionData(successTableRef);
},
// 这个方法你自己写在上边,不要放在这里,我这里是render 的过程,这里只是让你看的比较顺眼
setDefaultSelectionData = (successTableRef) => {
//在这里进行判断,让有启用的数据并且有选中的数据进行push 展示
if (!this.enableFlag && this.sceneIds?.length > 0) {
const dataSource = successTableRef.dataSource;
const selectedRowKeys = [];
const selectedRows = [];
this.sceneIds.forEach((itemid) => {
const row = dataSource.find((it) => it.id == itemid);
if (row) {
selectedRowKeys.push(itemid);
selectedRows.push(row);
}
});
const selectionData = {
selectedRowKeys,
selectedRows,
length: selectedRowKeys.length
};
setTimeout(() => {
this.tableRef?.setSelectionData(selectionData);
}, 0);
}
};
在保存页面
// 保存采购场景按钮
save = async (selectionData?: any) => {
const item = selectionData.selectedRows.map(
({ sceneCode, id, sceneName, es7 }) => ({
sceneCode,
sceneId: id,
sceneName,
es7
})
);
let params = {
defineId: this.props?.match?.params?.id,
params: item
};
const res = await service.addScene(params);
if (res && res.success === true) {
this.setState({});
ElNotification({ type: 'success', message: res.msg });
// 保存完成后自动跳转到指定页面
const { store } = this.props
store.MultiTabMobx.closeCurrentToPath('/fin/purcSettlement/Buyer');
} else {
ElNotification({
type: 'error',
message: res.msg
});
}
};