一.新建Vue2项目
vue create demo
二.安装引入Antd
1.安装Antd
yarn add ant-design-vue@1.7.8
2.引入Antd
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
//引入svg
import './icons'
Vue.config.productionTip = false
import Antd from 'ant-design-vue';
import 'ant-design-vue/dist/antd.css';
Vue.use(Antd);
/* eslint-disable no-new */
//runtime
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app")
三.修改组件代码
<template>
<a-form-model ref="tableform" :model="form">
<a-table :columns="columns" :data-source="form.tableData" :row-key="(record) => record.id" :pagination="false" :loading="loading">
<template v-for="col in ['name','age','address']" :slot="col" slot-scope="text, record, index">
<div :key="col">
<a-form-model-item v-if="record.editable" :prop="'tableData.'+index+'.'+col" :rules="rules[col]">
<a-input :ref="'input'+col" v-model="record[col]" @blur="e => handleBlur(e.target.value, record.key, col)"/>
</a-form-model-item>
<template v-else>
<span style="display:inline-block;width: 100%;" @click="e => edit(e.target.value, record.key, col)">{{text}}</span>
</template>
</div>
</template>
</a-table>
</a-form-model>
</template>
<script>
export default {
data() {
return {
columns:[
{
title: 'id',
align: 'center',
dataIndex: 'id',
key: 'id',
slots: { title: 'id' },
scopedSlots: { customRender: 'id' },
},{
title: 'name',
align: 'center',
dataIndex: 'name',
key: 'name',
slots: { title: 'name' },
scopedSlots: { customRender: 'name' },
},{
title: 'age',
align: 'center',
dataIndex: 'age',
key: 'age',
slots: { title: 'age' },
scopedSlots: { customRender: 'age' },
},{
title: 'address',
align: 'center',
dataIndex: 'address',
key: 'address',
slots: { title: 'address' },
scopedSlots: { customRender: 'address' },
}
],
loading: false,
editingKey: '',
form:{
tableData:
[
{id:1,key:1,name:'张三',age:12,address:'河北保定'},
{id:2,key:2,name:'李四',age:24,address:'河南驻马店'}
]
},
rules: {
name: { required: true, message: '姓名不能为空!' },
age: { required: true, message: '年龄不能为空!' },
address: { required: true, message: '地址不能为空!' },
}
}
},
methods: {
edit(value, key, column) {
console.log(value, key, column)
const newData = [...this.form.tableData];
const target = newData.find(item => key === item.key);
this.editingKey = key;
if (target) {
target.editable = true;
this.form.tableData = newData;
this.$nextTick(() => {
let id = 'input' + column
console.log(this.$refs[id])
this.$refs[id][0].focus()
})
}
},
handleBlur (value, key, column) {
this.$refs.tableform.validate(async valid => {
if (valid) {
const newData = [...this.form.tableData];
const target = newData.find(item => key === item.key);
this.editingKey = key;
if (target) {
delete target.editable
this.form.tableData = newData;
}
//调取编辑接口
this.$message.success('提交成功')
}
})
},
}
}
</script>
<style scoped>
/deep/.ant-form-item {
margin: 0 !important;
}
/deep/.ant-table-row {
height: 75px;
}
</style>
如果文章有帮助的话,欢迎一键三连,感谢支持!