问题描述
这两天在学习vue框架,并使用ant-design的table组件来显示用户信息,后端用springboot框架,当使用axios来进行数据交互时,无法获取到table中的参数key,具体信息如下:
页面:
点击删除标签后报错信息:
相关代码
<template>
<div id="user">
<h2>用户管理</h2>
<div>
<a-table bordered :dataSource="dataSource" :columns="columns" rowKey="id">
<template slot="name" slot-scope="text, record">
<editable-cell :text="text" @change="onCellChange(record.key, 'name', $event)"/>
</template>
<template slot="operation" slot-scope="text, record">
<a-popconfirm
v-if="dataSource.length"
title="你确定要删除?"
@confirm="() => onDelete(record.key)">
<a href="javascript:;">删除</a>
</a-popconfirm>
</template>
</a-table>
</div>
</div>
</template>
<script>
import axios from 'axios'
import qs from 'qs'
import EditableCell from './EditableCell'
export default {
name: 'UserManagement',
components: {
EditableCell
},
data() {
return {
dataSource: [],
columns: [{
title: 'id',
dataIndex: 'id',
},{
title: '姓名',
dataIndex: 'name',
width: '20%',
scopedSlots: { customRender: 'name' },
}, {
title: '性别',
dataIndex: 'sex',
},{
title: '密码',
dataIndex: 'password',
},{
title: '邮箱',
dataIndex: 'email',
},{
title: '地址',
dataIndex: 'address',
},{
title: '操作',
dataIndex: 'operation',
scopedSlots: { customRender: 'operation' },
}]
}
},
mounted: function (){
this.allUser();
},
methods: {
allUser(){
axios.get('http://localhost:8090/demo/all')
.then((res)=>{
this.dataSource = res.data
})
.catch((error)=>{
alert(error)
});
},
onCellChange (key, dataIndex, value) {
const dataSource = [...this.dataSource]
const target = dataSource.find(item => item.key === key)
if (target) {
target[dataIndex] = value
this.dataSource = dataSource
}
},
onDelete (key) {
alert(key)
axios.get('http://localhost:8090/demo/deleteById?id='+key)
.then((res)=>{
alert(res.data)
})
.catch((error)=>{
alert(error)
});
const dataSource = [...this.dataSource]
this.dataSource = dataSource.filter(item => item.key !== key)
},
}
}
</script>
controller层:
@GetMapping(path="/deleteById")
public @ResponseBody String deleteById(@RequestParam Integer id){
System.out.println(id);
userRepository.deleteById(id);
return "Delete success!";
}
好像是dataSource中必须要有key,比如说这样的数据:
dataSource: [{
key: '0',
name: 'Edward King 0',
age: '32',
address: 'London, Park Lane no. 0',
}, {
key: '1',
name: 'Edward King 1',
age: '32',
address: 'London, Park Lane no. 1',
}]
但是我后端返回的数据中没有key这个属性,而是id。之前尝试把数据库中的主键id的字段名换成key,但是key又是MySQL中的关键字,用不了。
求大神们指教,这个key的问题要怎么处理?或者有没有其他处理办法?
我看你table里面有id这个字段,你就把后端传给前端的id赋值给table的id, 同时在遍历数据的时候,把id值赋值给key