对element table的增删改查功能封装成mixin
<template>
<div>
<el-table :data="tableData">
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="age" label="年龄"></el-table-column>
<el-table-column label="操作">
<template slot-scope="scope">
<el-button size="mini" @click="editItem(scope.row)">编辑</el-button>
<el-button size="mini" @click="removeItem(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<el-dialog :visible="dialogVisible" title="编辑" @close="closeDialog">
<el-form ref="form" :model="editForm" label-width="80px">
<el-form-item label="姓名" prop="name">
<el-input v-model="editForm.name"></el-input>
</el-form-item>
<el-form-item label="年龄" prop="age">
<el-input v-model="editForm.age"></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="closeDialog">取消</el-button>
<el-button type="primary" @click="saveItem">保存</el-button>
</div>
</el-dialog>
<el-button type="primary" @click="addItem">添加</el-button>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
tableData: [],
dialogVisible: false,
editForm: {}
};
},
created() {
this.loadData();
},
methods: {
// 加载数据
loadData() {
axios.get('your_api_endpoint').then(response => {
this.tableData = response.data;
}).catch(error => {
console.log(error);
});
},
// 添加
addItem() {
this.dialogVisible = true;
this.editForm = {};
},
// 编辑
editItem(row) {
this.dialogVisible = true;
this.editForm = { ...row };
},
// 保存
saveItem() {
if (this.$refs.form.validate()) {
// 若 editForm 里存在 id,则为修改已有数据
if (this.editForm.id) {
axios.put(`your_api_endpoint/${this.editForm.id}`, this.editForm).then(() => {
this.loadData();
}).catch(error => {
console.log(error);
});
} else {
axios.post('your_api_endpoint', this.editForm).then(() => {
this.loadData();
}).catch(error => {
console.log(error);
});
}
this.dialogVisible = false;
}
},
// 删除
removeItem(row) {
axios.delete(`your_api_endpoint/${row.id}`).then(() => {
this.loadData();
}).catch(error => {
console.log(error);
});
},
// 关闭对话框
closeDialog() {
this.dialogVisible = false;
this.$refs.form.resetFields();
}
}
};
</script>
注:请求需要由后台的参与,并不是纯前端增删改查