antd升级到v3,需先将vue更到3.2以上。
接下来分两步走:
一、更新依赖
npm update vue
npm update ant-design-vue
npm update @ant-design/icons-vue
分别安装的是最新版的vue@3.2.33、ant-design-vue@3.2.3、@ant-design/icons-vue@6.1.0
注:期间我分别把core-js、@vue/cli-plugin-babel、@vue/cli-service、@vue/compiler-sfc也都更新了最新版本,如果运行还有问题可以试试。
运行项目是成功的,但是浏览器访问有Table组件的页面时报错(且如果页面在onBeforemount中调用了查询接口,会一直不停请求,浏览器直接崩溃):
可以看到是Table组件报错了Object.fromEntries is not a function
Object.fromEntries是ES10的用法,我们需要安装polyfill-object.fromentries
npm i polyfill-object.fromentries
并在main.js(或main.ts)中引入
import "polyfill-object.fromentries";
再运行就不报错了,Table组件也能正常渲染。
二、组件改动
因为没有用到自定义表单,所以暂时项目中只改动了Table组件和日期格式,就以这两个为例。
1、Table组件
(1)slots
改动前:
const columns = [
{
title: "人员数量",
dataIndex: "staffNum",
key: "staffNum",
ellipsis: true,
},
{
title: "操作人",
dataIndex: "modifyByName",
key: "modifyByName",
ellipsis: true,
},
{
title: "操作时间",
dataIndex: "modifyTime",
slots: {
customRender: "modifyTime",
},
},
];
单元格渲染方式是v-slot:key:
<template #modifyTime="{ record }">
{{ record.modify }}
</template>
改动后:
const columns = ref([
{
title: "人员数量",
dataIndex: "staffNum",
key: "staffNum",
ellipsis: true,
},
{
title: "操作人",
dataIndex: "modifyByName",
key: "modifyByName",
ellipsis: true,
},
{
title: "操作时间",
dataIndex: "modifyTime",
key: "modifyTime",
ellipsis: true,
},
]);
单元格渲染方式是v-slot:bodyCell
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'modifyTime'">
{{ record.modifyTime }}
</template>
</template>
(2)列伸缩:resizable
a-table组件设置:
columns设置:
const columns = ref([
{
title: "区域ID",
dataIndex: "id",
key: "id",
resizable: true,
width: 200,
ellipsis: true,
}
]);
其中resizable和width组合出现,width必须是number。
定义handleResizeColumn方法:
setup() {
return {
formData,
loading,
columns,
handleResizeColumn: (w, col) => {
col.width = w;
},
};
}
2、日期组件使用更轻量级的dayjs
npm i dayjs
定义公共方法toLocalDate.js:
import dayjs from "dayjs";
function toLocalDate(date, tip, type = "-") {
if (!date) {
return null
}
let fmt = "YYYY" + type + "MM" + type + "DD HH:mm:ss";
if (tip == 'day') {
// 年月日
fmt = "YYYY" + type + "MM" + type + "DD";
} else if (tip == 'min') {
// 年月日时分
fmt = "YYYY" + type + "MM" + type + "DD HH:mm";
}
return dayjs(date).format(fmt);
}
export default toLocalDate
main.js引入
import toLocalDate from './common/js/toLocalDate.js';
let app = null;
function render(props = {}) {
app = createApp(App)
app.config.globalProperties.$toLocalDate = toLocalDate;
app.mount('#app');
}
组件中使用:
<template>
{{ $toLocalDate(new Date(record.joinDate), "day") }}
</template>