今天记录一下,关于列数据过滤与组件通信之间很好的结合,并纪念一下我的踩坑经过。
目录
一、父组件
<template>
<div>
<sheet :title="title"
:tableHead="tableHead"
:tableData="tableData"
:pageNum.sync="workOrder.pageNum"
:total="workOrder.total"
@page-mode="queryThingsByPage"
:hasPagination="true">
</sheet>
</div>
</template>
<script>
//此处需要在引号里写入正确的子组件的路径
import sheet from './sheet.vue'
export default {
data () {
return {
title: '测试表格',
tableHead: [
{
label: '学号',
prop: 'no'
},
{
label: '姓名',
prop: 'name'
},
{
label: '性别',
prop: 'sex',
formatter: this.sexFormat
},
{
label: '总分',
prop: 'scores'
}
],
tableData: [
{
no: 'TNT001',
name: '花心筒',
sex: 'M',
scores: 500
},
{
no: 'TNT002',
name: '雀巢',
sex: 'F',
scores: 666
},
{
no: 'TNT003',
name: '梦龙',
sex: 'M',
scores: 389
},
{
no: 'TNT004',
name: '可爱多',
sex: 'F',
scores: 389
}
]
}
},
//装载子组件
components: {sheet},
methods: {
sexFormat (row, column, cellValue, index) {
if (cellValue === 'M') {
return '男'
} else if (cellValue === 'F') {
return '女'
} else {
'未登记'
}
},
queryThingsByPage: {
//此处省略分页查询实体
}
}
}
</script>
二、table子组件
<template>
<div class="sheet-box">
<div class="sheet-title" v-if="title">{{title}}</div>
<div class="sheet-content">
<el-table :data="tableData" stripe>
<el-table-column
class="tableHead"
v-for="item in tableHead"
:prop="item.prop"
:label="item.label"
:width="item.width"
:formatter="item.formatter">
</el-table-column>
<slot name="remark" v-if="hasRemark"></slot>
</el-table>
<el-pagination
class="sheet-content-page"
v-if="hasPagination"
small
layout="prev, pager, next"
:current-page.sync="page"
:total="total"
@current-change="queryPage">
</el-pagination>
</div>
</div>
</template>
<script>
export default {
data () {
return {
page: this.pageNum
}
},
components: {},
props: {
title: {
type: String,
default: ''
},
tableHead: {
type: Array,
default: [],
required: true
},
tableData: {
type: Array,
default: [],
required: true
},
hasRemark: {
type: Boolean,
default: false
},
hasPagination: {
type: Boolean,
default: false
},
pageNum: {
type: Number,
default: 1
},
total: {
type: Number,
default: 0
}
},
methods: {
queryPage (currentPage) {
this.$emit('update:pageNum', currentPage)
this.$emit('page-mode')
}
}
}
</script>
<style lang="less">
.sheet-box {
.sheet-title {
padding: 10px 0;
}
.sheet-content {
width: 100%;
margin-bottom: 20px;
/deep/ .el-table th {
background-color:#EBEEF5 !important;
}
.sheet-content-page {
float: right;
}
}
}
</style>
三、父组件与子组件通信原理
1. 父组件传递消息给子组件
依靠子组件的props。props里的属性的值是只读的;如果修改,vue会报warn。
2. 子组件传递修改的消息给父组件
子组件props中的属性pageNum,赋值给子组件局部变量属性page,然后修改局部变量page(供页面数据渲染的由page代替),通过this.$emit()来更新子组件props属性pageNum的值。
在父组件中,引用子组件sheet,要在pageNum这个属性后面加上.sync,表示将子组件pageNum的值传递到父组件中。
此时,子组件传递修改的消息给父组件的流程才算走完。
四、列数据过滤
我建议,将过滤器写在方法中,利用element ui列属性的formatter,将过滤方法通过父组件传递到子组件中,直接完成列数据的过滤,而不用写插槽来专门过滤某一列。这样做,可以在js中自由操控表头和数据,不用修改页面,更方便快捷。
五、踩坑经过
暂略,等我整理好思绪,将我的奇葩想法再写上来