<template>
<a-layout class="main">
<div class="query">
<a-input-search placeholder="输入名称" style="width: 200px" @search="onSearch" enterButton v-model="queryData.name" />
<a-button class="btn" type="primary" v-if="isHasPermission()('sys.dict.save')" @click="addRow">新增</a-button>
<a-button v-show="selectedRowKeys.length > 0 && isHasPermission()('sys.dict.delete')" class="btn" type="danger"
@click="deleteData">删除
</a-button>
</div>
<div class="table-wrapper">
<a-table :locale="{'emptyText':'暂无数据'}" :pagination="pagination" :loading="loading" :columns="columns"
:dataSource="data">
<template v-for="(col, i) in ['id','name','num', ]" :slot="col" slot-scope="text, record">
<a-input :key="col" v-if="record.editable" style="margin: -5px 0" :value="text" :placeholder="columns[i].title"
:ref="`${record.key}`"
@change="e => handleChange(e.target.value, record.key, col)" />
<template v-else>{{ text }}</template>
</template>
<template slot="type" slot-scope="text, record">
<a-select placeholder="请选择" v-if="record.editable" style="display: block;" @change="onChangeSelect($event, record,'type')"
v-decorator="['type',{rules: [{ required: true,message:'请选择设备类型'}]}]" :value="text">
<a-select-option value="1">巡检时间计划</a-select-option>
<a-select-option value="2">保养时间计划</a-select-option>
</a-select>
<template v-else>{{ text==1? '巡检时间计划':text==2? '保养时间计划':'' }}</template>
</template>
<template slot="control" slot-scope="text, record">
<div class="editable-row-operations">
<div v-if="record.editable"> <a @click="save(record)">保存</a>
<a-divider type="vertical" /> <a @click="cancel(record.key)">取消</a> </div>
<div v-else> <a @click="edit(record.key)">编辑</a> </div>
</div>
</template>
</a-table>
</div>
</a-layout>
</template>
<script>
import {
mapGetters
} from 'vuex'
import api from '@/api'
const columns = [{
title: 'id',
dataIndex: 'id'
}, {
title: '名称',
dataIndex: 'name',
width: '30%',
scopedSlots: {
customRender: 'name'
}
}, {
title: '字典类型',
dataIndex: 'type',
width: '30%',
scopedSlots: {
customRender: 'type'
}
}, {
title: '字典码',
dataIndex: 'num',
width: '30%',
scopedSlots: {
customRender: 'num'
}
}, {
title: '操作',
dataIndex: 'control',
scopedSlots: {
customRender: 'control'
}
}]
export default {
data() {
return {
data: [],
columns,
selectedRowKeys: [],
selectedItems: [],
loading: false,
queryData: {
name: '',
page: 1,
limit: 10
},
pagination: {
showSizeChanger: true,
total: 0,
current: 0,
showTotal: total => `共 ${total} 条数据`,
onChange: this.pageChange,
onShowSizeChange: (current, pageSize) => this.queryData.limit = pageSize
},
visible: false,
confirmLoading: false,
form: this.$form.createForm(this),
// 表格缓存的数据 - 用来点击取消时回显数据
cacheData: [],
fields:['name', 'type', 'num'],
labelCol: {
xs: {
span: 24
},
sm: {
span: 7
}
},
wrapperCol: {
xs: {
span: 24
},
sm: {
span: 13
}
},
curSelect: [],
options: []
}
},
computed: {
...mapGetters(['color'])
},
mounted() {
if (!this.isHasPermission()('sys.dict.list')) {
return
}
this.loadData() //加载数据
},
methods: {
...mapGetters(['isHasPermission']),
onSelectChange(selectedRowKeys, selectedItems) {
this.selectedRowKeys = selectedRowKeys
this.selectedItems = selectedItems
},
onSearch() {
this.queryData.page = 1
this.loadData()
},
pageChange(page) {
this.queryData.page = page
this.loadData()
},
// 添加一行
addRow() {
if (this.data.some(item => item.newRow === true)) return this.$message.info('请先编辑完毕后在再添加!');
// 新增时取消表格选中的key
this.selectedRowKeys = []
this.data.unshift({
key: 'newRow', // newRow 表示该行是新增的,提交成功后 key替换为数据库ID
newRow: true, //用来限制只能新增一行
name: '',
type: '',
num: '',
editable: true
})
this.cacheData.unshift({
key: 'newRow', // newRow 表示该行是新增的,提交成功后 key替换为数据库ID
newRow: true, //用来限制只能新增一行
name: '',
type: '',
num: '',
editable: false
})
},
// validateRow可以提取为公共函数
validateRow(key, fields, callback) {
// 查找验证是否通过
const row = {};
let err = false;
// forEach 对每一个验证,可以更改为some满足一个就提醒
fields.forEach(filed => {
let refName = `${filed}`;
console.log(refName)
let result = this.$refs[refName].validate();
row[filed] = result.value;
if (!result.success) {
err = true;
}
});
callback(err, row);
},
// 点击保存
save(record) {
const newData = [...this.data];
const target = newData.filter(item => record.key === item.key)[0];
//如果做非空判断在target处做判断
let url = api.timePlan.saveOrUpdate;
if (target) {
this.$http({
url: url,
method: 'post',
headers: {
send: 'json'
},
data: target
}).then(res => {
const newData = [...this.data];
const target = this.data.find(item => item.key === record.key)
if (res.code == 0) {
this.loadData();
// 根据rowKey判断该行数据是否存在
/* if (target) {
console.log(JSON.stringify(target))
target.editable = false
target.newRow = false
this.data = newData;
this.loadData();
} */
}
})
}},
// 点击取消
cancel(rowKey) {
const newData = [...this.data];
const newNewData = newData.filter(item => "newRow" != item.key);
const target = newData.filter(item => rowKey === item.key)[0];
if (target) {
// 将缓存数据中匹配到的数据对象覆盖合并当前被修改的行
Object.assign(target, this.cacheData.filter(item => rowKey === item.key)[0]);
delete target.editable;
this.data = newNewData;
}
},
handleChange(value, key, column) {
const itemData = [...this.data]
const target = itemData.find(item => key === item.key)
if (target) {
target[column] = value
this.data = itemData
}
},
onChangeSelect(value, row, column) {
const itemData = [...this.data]
const target = itemData.find(item => row.key === item.key)
if (target) {
target[column] = value
this.data = itemData
}
},
edit(key) {
const newData = [...this.data];
const target = newData.filter(item => key === item.key)[0];
// 根据rowKey判断该行数据是否存在
if (target) {
target.editable = true; // 修改target可以直接影响到newData
this.data = newData;
}
},
loadData() {
this.loading = true
this.$http.post(api.timePlan.list, this.queryData).then(res => {
this.loading = false
/*获取页面返回的数据*/
this.data = res.page.list;
this.data.forEach((item, index) => {
item.key = item.id;
item.editable = false; //设置为不可编辑
item.newRow = false;
})
this.cacheData = JSON.parse(JSON.stringify(this.data)); //这样转换相当于去除了引用关系 是一个单独的数组 不会因为this.data 改变他跟着改变
this.pagination.total = res.page.totalCount
this.pagination.current = res.page.currPage
}).catch(err => {
console.log(err)
})
},
deleteData() {
let arr = []
this.selectedItems.forEach(item => {
arr.push(item.id)
})
if (arr.length < 1) {
this.$message.error('请最少选则一条数据操作')
}
const self = this
this.$confirm({
title: '删除操作!',
content: '您是否要删除选中项?',
okText: '确认',
okType: 'danger',
cancelText: '取消',
onOk() {
return new Promise((resolve, reject) => {
self.$http({
url: api.dict.deleteBatch,
method: 'post',
headers: {
send: 'json'
},
data: arr
}).then(res => {
self.$message.success('删除成功!')
for (let i in self.selectedItems) {
self.deleteHtmlData(self.selectedItems[i], self.data)
}
self.selectedRowKeys.length = 0
resolve()
})
}).catch((e) => console.log(e))
},
onCancel() {}
})
},
deleteHtmlData(targetData) {
let indexOf = this.indexOf(targetData, this.data, 'id')
if (indexOf != -1) {
this.pagination.total = this.pagination.total - this.selectedItems.length;
this.data.splice(indexOf, 1)
}
if (this.data.length == 0) {
this.loadData()
}
},
handleCancel() {
this.visible = false
}
}
}
</script>
<style lang="less" scoped>
.main {
padding: 25px;
background: #fff;
.query {
margin-bottom: 25px;
.btn {
margin-left: 10px;
}
}
}
</style>