🌟前言
大家好,上一期的Vue实战都阅读了吗?上一期主要是对Vuex的一个基本操作,通过Vuex我们可以实现全局的状态(数据)共享,以便与我们更好的实现一些需求。
不知道大家在日常工作当中是否被频繁的列表增删改查困扰,功能很简单但确实是非常繁琐的一项工作;今天这一期呢我会从Vue2父子组件如何传值并结合Element来封装一个简单的列表组件;一次封装,多次复用。
🌟table组件封装
在你的component目录下创建一个Table.vue:
<template>
<el-card class="box-card" style="width: 100%;height: 100%">
<div class="btnBox">
<el-button v-for="(item,index) in tableOperation" :key="index" :type="item.type" size="small" @[eventName]="handleClick(item.fun, multipleSelection)">{
{
item.label }}</el-button>
</div>
<el-table
style="margin-bottom: 20px"
:data="tableData"
size="small"
row-class-name="row"
cell-class-name="column"
:highlight-current-row="true"
fit
@selection-change="handleSelectionChange"
>
<!--这是是为了将表格设置成带有选择框的表格-->
<el-table-column
type="selection"
width="55"
/>
<el-table-column
v-for="(item, index) in tableLabel"
:key="index"
align="center"
:prop="item.prop"
:width="item.width"
:label="item.label"
/>
</el-table>
<div class="block" style="text-align: end">
<el-pagination
background
:current-page="1"
:page-sizes="[10, 20, 30, 40]"
:page-size="10"
layout="total, sizes, prev, pager, next, jumper"
:total="tableData.length"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
/>
</div>
</el-card>
</template>
<script>
export default {
name: 'Table',
// 因为是子组件,要接受父组件传递的数据,所以这里我们定义props
props: {
tableData: {
// 父组件传递过来的表格数据
type: Array,
default: () => {
return []
}
},
tableLabel: {
// 父组件传递过来的表头数据
type: Array,
default: () => {
return []
}
},
tableOperation: {
// 父组件传递过来的操作按钮数据
type: Array,
default: () => {
return []
}
}
},
data() {
return {
eventName: 'click', // 点击按钮绑定的方法,这样写法也可以去绑定一些其他的比如change等方法
multipleSelection: [] // 这个数组用来保存被选择行的数据,顺序是按照你勾选的顺序来排序的
}
},
methods: {
// @selection-change方法可以监听到表格里哪一行被选中,类型是数组;
// 然后我们将它赋值给定义好的 multipleSelection
handleSelectionChange(val) {
this.multipleSelection = val
},
// 动态绑定操作按钮的点击事件(按钮是父组件传递过来循环出来的,所以我们给按钮定义一个方法)
// 接收两个参数,一个是fun(string类型),一个是row(array类型,也就是我们选中行的数据)
// 这里的某个按钮时传递的参数
// 比如我点击的是编辑,那这时的fun就是 'edit',执行的方法就是下边的this.edit(row)
handleClick(fun,row) {
this[fun](row)
},
edit(row) {
if (!row.length) {
this.$message.error(

1万+



被折叠的 条评论
为什么被折叠?



