二次封装element-ui table,操作列手动传入按钮

我们在使用element-ui时,必定会用到表格这个组件,虽然element组件已经为我们封装很好了。但是我们在实际开发中会根据我们的业务在element-ui的基础上再次封装,比如表格最后一列会经常有操作这一列,对应着不同的按钮,像编辑按钮、查看按钮、删除按钮等,有些表格的结构类似,显示数据和操作,差别只是在于后边操作按钮不相同,此时,封装一个业务组件,手动传入需要的按钮,这样,在遇到类似的情况就可以直接使用该业务组件。具体 实现思路如下:

basicTable.vue组件

        <el-table
            :data="tableData"
            stripe
            @selection-change="handleSelectionChange"
            style=" 100%;">
            <el-table-column
                v-if="isCheckbox"
                type="selection"
                
                width="50">
            </el-table-column>
            <el-table-column
                v-for="column in tableHeader"
                :key="column.label"
                :label="column.label"
                :width="column.width">
                <template slot-scope="scope">
                    <span>{{ scope.row[column.prop] }}</span>
                </template>
            </el-table-column>
            <el-table-column
                label="操作"
                v-if="isOperate">
                <template slot-scope="scope">
                    <slot :row='scope.row' :index='scope.$index'></slot>
                </template>
            </el-table-column>
            <div slot="empty">
                <span>暂无数据</span>
            </div>
        </el-table>    

要想实现想要的功能,最重要的是slot那段代码,我使用的是slot插槽,用来接收父组件传进来的数据,这样一来,我们在父组件调用basicTable组件时,传入需要显示的按钮,这样按钮就会在slot插槽的位置显示出来。

在父组件中使用BasicTable.vue

        <BasicTable :isOperate='true' :tableHeader="tableHeader" :isCheckbox='true' @isSelectCheck="isSelectCheck">
            <template slot-scope="data">
                <el-button
                v-if="false"
                size="mini"
                type="primary"
                @click="attention(data.index, data.row)">互关</el-button>
                <el-button
                v-else
                size="mini"
                type="danger"
                @click="cancelAttention(data.index, data.row)">取关</el-button>
            </template>
        </BasicTable>    

在父组件中使用基础组件时,在basictable标签中传入要使用的按钮。最最容易入坑的是在绑定事件的时候,我在互关的按钮绑定点击事件attention,在传入参数的时候,怎么让按钮点击的时候拿到当前列和表格数据,我们在直接使用element提供的table的时候,可以直接绑定点击事件,就像这样

<el-table-column label="操作">
      <template slot-scope="scope">
        <el-button
          size="mini"
          @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        <el-button
          size="mini"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
</el-table-column>

但是我哦们把template里边的内容换成了<slot></slot>

我们可以通过slot将scope传到父组件,在这里最最需要注意的是需要什么数据就传什么数据,就像在basictable.vue代码中那样 ,虽然我们可以通过scope拿到表格的相关数据,但是不能直接通过slot直接将scope传出去,至于为什么,就不知道了。为了和之前的scope区别开,我在父组件中接收的时候起了个名字叫data,其实叫scope叫什么都无所谓,这样,就能拿到想要的数据了。

原文地址:https://www.cnblogs.com/zmyxixihaha/p/11578347.html