把文件中的页面使用Composition API重构要求用vue2完成并详细到每个方法
时间: 2024-11-09 21:20:22 浏览: 11
使用Vue Composition API写出清晰、可扩展的表单实现
为了将文件中的代码从Options API重构为Composition API,并保持Vue 2的支持,我们可以使用`@vue/composition-api`插件。以下是详细的重构步骤和代码:
### 安装依赖
首先,需要安装`@vue/composition-api`插件:
```sh
npm install @vue/composition-api
```
### 主要更改点
1. **引入 Composition API**:在组件中引入`setup`函数和其他Composition API相关的钩子。
2. **状态管理**:使用`reactive`或`ref`来声明响应式数据。
3. **生命周期钩子**:使用相应的Composition API钩子,如`onMounted`、`onCreated`等。
4. **方法提取**:将原有的方法提取到`setup`函数中。
### 重构后的代码
```vue
<template>
<a-spin :spinning="spinning" tip="报表同步中,请稍等">
<a-card :bordered="false">
<!-- 查询区域 -->
<div class="table-page-search-wrapper">
<a-form layout="inline" @keyup.enter.native="searchQuery">
<a-row :gutter="24">
<a-col>
<my-fast-date-picker
:radioList="[{ value: 2, text: '月' }, { value: 3, text: '年' }]"
:radioVal="2"
:currName="'近半年'"
:showRadioGroup="true"
:fastTime="fastTime"
@change="change"
>
<template v-slot:text>时间:</template>
</my-fast-date-picker>
</a-col>
<template v-if="toggleSearchStatus">
<a-col :xl="6" :lg="7" :md="8" :sm="24">
<a-form-item label="项目编号:">
<a-input placeholder="请输入项目编号" allowClear v-model="queryParam.projectCode" />
</a-form-item>
</a-col>
<a-col :xl="6" :lg="7" :md="8" :sm="24">
<a-form-item label="项目名称">
<a-select
allowClear
show-search
v-model="queryParam.projectName_Code"
placeholder="请输入项目名称"
style="width: 100%"
:show-arrow="false"
:filter-option="false"
:not-found-content="null"
@search="projectCodeSearch"
@change="projectCodeChange"
>
<a-select-option v-for="d in projectNameList" :key="d.id">
{{ d.text }}
</a-select-option>
</a-select>
</a-form-item>
</a-col>
<a-col :xl="6" :lg="7" :md="8" :sm="24">
<a-form-item label="物资">
<a-input placeholder="请输入物资编号/名称" allowClear v-model="queryParam.keyWord" />
</a-form-item>
</a-col>
<a-col :xl="6" :lg="7" :md="8" :sm="24">
<a-form-item label="厂商">
<j-search-select-tag
placeholder="请选择厂商"
v-model="queryParam.producerId"
dict="biz_product_vendor,abbreviation,id,del_flag = 0 and status = 1"
/>
</a-form-item>
</a-col>
<a-col :xl="6" :lg="7" :md="8" :sm="24">
<a-form-item label="规格型号">
<a-input placeholder="请输入规格型号" allowClear v-model="queryParam.specification" />
</a-form-item>
</a-col>
</template>
<a-col :xl="6" :lg="7" :md="8" :sm="24">
<span style="float: left; overflow: hidden;" class="table-page-search-submitButtons">
<a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
<a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
<a @click="handleToggleSearch" style="margin-left: 8px">
{{ toggleSearchStatus ? '收起' : '展开' }}
<a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
</a>
</span>
</a-col>
</a-row>
</a-form>
</div>
<!-- 查询区域-END -->
<!-- 操作按钮区域 -->
<div class="table-operator">
<div>
<a-button type="primary" icon="download" @click="handleExportXlsx()">导出</a-button>
</div>
</div>
<!-- table区域-begin -->
<div>
<a-table
ref="table"
size="middle"
:scroll="{ x: true }"
bordered
rowKey="uniqueId"
:columns="columns"
:dataSource="dataSource"
:pagination="ipagination"
:loading="loading"
class="j-table-force-nowrap"
@change="handleTableChange"
>
<span slot="receivingFreezeAmount">
领用冻结
<a-tooltip>
<template slot="title">
项目领用申请审核通过后,待出库的数量。
</template>
<a-icon type="info-circle" />
</a-tooltip>
</span>
<span slot="receivingFreezeAmount_title">
预算余量
<a-tooltip>
<template slot="title">
预算余量=预算总数-领用冻结-领用总数+领用归还
</template>
<a-icon type="info-circle" />
</a-tooltip>
</span>
<span slot="requisitionAmount_title">
领用总数
<a-tooltip>
<template slot="title">
项目盘盈更新领用余料时,会自动产生领用增补单(不受预算限制),可能导致领用总数超过预算总数。
</template>
<a-icon type="info-circle" />
</a-tooltip>
</span>
<span slot="budgetTotalAmount" slot-scope="text, record">
<a-tooltip>
<template slot="title">
<d1v class="tipItem">
<div>预算编号</div>
<div>预算数</div>
</d1v>
<div v-for="(value, key) in record.budgetDetail" class="tipItem" v-show="key !== '小计'">
<div>{{ key }}</div>
<div>{{ value }}</div>
</div>
<div class="tipItem">
<div>小记</div>
<div>{{ text }}</div>
</div>
</template>
<span style="color: blue">{{ text }}</span>
</a-tooltip>
</span>
<span slot="budgetSurplusAmount" slot-scope="text, record">
<span :style="{ color: record.budgetSurplusAmount <= projectBudgetMarginWarning ? 'red' : 'black' }">{{ text }}</span>
</span>
<span slot="inventoryAmount" slot-scope="text, record">
<span :style="{ color: record.inventoryAmount <= record.budgetSurplusAmount ? 'red' : 'black' }">{{ text }}</span>
</span>
</a-table>
</div>
</a-card>
</a-spin>
</template>
<script>
import { createNamespacedHelpers, reactive, computed, watch, onMounted } from '@vue/composition-api';
import MyFastDatePicker from '@/components/date/MyFastDatePicker';
const { mapActions } = createNamespacedHelpers('someNamespace');
export default {
name: 'ProjectMaterialStatistics',
setup(props, context) {
const state = reactive({
projectNameList: [],
projectName_Code: "",
projectBudgetMarginWarning: 0,
expandedRowKeys: [],
workorderProjectList: [],
description: '营业报表管理页面',
fastTime: ['本月', '上月', '近半年'],
noCreate: true,
hasUpdateTime: true,
configOrderSubTypeList: [],
configOrderSubTypeTemp: undefined,
allDepartList: [],
hallCodeDataList: [],
spinning: false,
checkFlag: true,
updateTime: '',
url: {
list: "/web/projectUseMaterial/list",
exportXlsxUrl: "/web/projectUseMaterial/export",
exportPdfUrl: "/web/bizBusinessRecord/exportpdf",
exportDetailUrl: "/web/bizBusinessRecord/exportDetailExcel",
},
keyList: ['saleNum', 'saleName', 'terminalTypeName', 'userTypeName', 'configOrderMainTypeName', 'configOrderSubTypeName'],
ipagination: {
current: 1,
pageSize: 20,
pageSizeOptions: ['20', '50', '80'],
showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 条`,
showQuickJumper: true,
showSizeChanger: true,
total: 0
},
columns: [
{ title: '项目编号', align: "center", dataIndex: 'projectCode', customRender: (text, row, index) => renderMergedCells1(text, row, index) },
{ title: '项目名称', align: "center", dataIndex: 'projectName', customRender: (text, row, index) => renderMergedCells(text, row, index) },
{ title: '物资编号', align: "center", dataIndex: 'materialCode' },
{ title: '物资名称', align: "center", dataIndex: 'materialName' },
{ title: '厂商', align: "center", dataIndex: 'producerId_dictText' },
{ title: '规格型号', align: "center", dataIndex: 'specification' },
{ title: '单位', align: "center", dataIndex: 'unit' },
{ title: '预算总数', align: "center", dataIndex: 'budgetTotalAmount', scopedSlots: { customRender: 'budgetTotalAmount' } },
{ align: "center", slots: { title: 'receivingFreezeAmount' }, dataIndex: 'receivingFreezeAmount' },
{ align: "center", slots: { title: 'requisitionAmount_title' }, dataIndex: 'receivingTotalAmount' },
{ title: '领用余料', align: "center", dataIndex: 'receivingSurplusAmount' },
{ title: '领料使用', align: "center", dataIndex: 'receivingUseAmount' },
{ align: "center", dataIndex: 'budgetSurplusAmount', slots: { title: 'receivingFreezeAmount_title' }, scopedSlots: { customRender: 'budgetSurplusAmount' } },
{ title: '库存可用数', align: "center", dataIndex: 'inventoryAmount', scopedSlots: { customRender: 'inventoryAmount' } }
],
dataSource: []
});
const { commit } = context;
const queryParam = reactive({
projectCode: '',
keyWord: '',
producerId: '',
specification: '',
projectName_Code: '',
projectName: ''
});
const loadData = (page) => {
// 仿照原逻辑实现
// 示例调用接口
// fetch(state.url.list, { page })
// .then(response => response.json())
// .then(data => {
// state.dataSource = data.items;
// state.ipagination.total = data.total;
// });
};
const renderMergedCells = (value, row, index) => {
const obj = { children: value, attrs: {} };
if (index === 0 || row.projectName !== state.dataSource[index - 1].projectName) {
let rowSpan = 1;
for (let i = index + 1; i < state.dataSource.length; i++) {
if (state.dataSource[i].projectName === row.projectName) {
rowSpan++;
} else {
break;
}
}
obj.attrs.rowSpan = rowSpan;
} else {
obj.attrs.rowSpan = 0;
}
return obj;
};
const renderMergedCells1 = (value, row, index) => {
const obj = { children: value, attrs: {} };
if (index === 0 || row.projectCode !== state.dataSource[index - 1].projectCode) {
let rowSpan = 1;
for (let i = index + 1; i < state.dataSource.length; i++) {
if (state.dataSource[i].projectCode === row.projectCode) {
rowSpan++;
} else {
break;
}
}
obj.attrs.rowSpan = rowSpan;
} else {
obj.attrs.rowSpan = 0;
}
return obj;
};
const projectCodeSearch = (value) => {
getAction('/web/projectRecord/searchMainProject', { order: 'desc', pageNo: 1, pageSize: 100, keyword: value })
.then(res => {
state.projectNameList = res.result.map(item => ({
id: item.id,
value: item.projectCode,
text: item.projectName
}));
});
};
const projectCodeChange = (value) => {
const obj = state.projectNameList.find(item => item.id === value);
queryParam.projectName_Code = value;
if (obj) {
commit('setExportParams', { projectName: obj.text });
queryParam.projectName = obj.text;
} else {
commit('setExportParams', { projectName: '' });
queryParam.projectName = '';
}
};
const change = (val1, val2, val3) => {
state.exportParams.dateTpye = val3 === 2 ? 1 : 2;
queryParam.beginDate = val1;
queryParam.endDate = val2;
queryParam.hiddenZeroTotalAmountFlag = state.checkFlag ? 1 : 0;
// loadData(1);
};
const handelChange = () => {
state.configOrderSubTypeTemp = undefined;
queryParam.configOrderSubType = undefined;
queryParam.incomeExpenseType = '';
getConfigOrderSubTypeList();
};
const getConfigOrderSubTypeList = () => {
if (queryParam.configOrderMainType) {
getAction('/web/bizTransactionOrder/getOrderSubType', { configOrderMainType: queryParam.configOrderMainType })
.then(res => {
if (res.code === 200) {
switch (queryParam.configOrderMainType) {
case '1':
const arr = [];
res.result.forEach(v => arr.push([v]));
arr.forEach(v => v.push({ value: v[0].value, label: v[0].label + '(退)' }));
state.configOrderSubTypeList = arr.flat().filter(v => ![96, 98].includes(Number(v.value)));
break;
case '2':
state.configOrderSubTypeList = res.result.filter(v => [1, 2, 3, 4, 5, 6, 7, 15, 16, 20, 21].includes(Number(v.value)));
break;
case '3':
state.configOrderSubTypeList = res.result.filter(v => ![7, 8, 10, 12, 14, 16].includes(Number(v.value)));
break
阅读全文