el-table行点击事件row-click与列按钮事件冲突

需求简述

表格用el-table实现,操作列的编辑按钮点击事件正常实现。现要为行加一点击事件,即row-click。加上后,发现点击操作列的编辑按钮时,会触发按钮本身事件,同时会触发行点击事件。第一版代码如下:

<template>
    <el-table :data="tableData" border @row-click="rowClick">
        <el-table-column prop="date" label="日期" width="150"></el-table-column>
        <el-table-column prop="name" label="姓名" width="120"></el-table-column>
        <el-table-column prop="province" label="省份" width="120"></el-table-column>
        <el-table-column prop="city" label="市区" width="120"></el-table-column>
        <el-table-column label="操作" width="100">
            <template slot-scope="scope">
                <el-button @click="handleClick(scope.row)" type="text" size="small">编辑</el-button>
            </template>
        </el-table-column>
    </el-table>
</template>
 
<script>
 export default {
   methods: {
      handleClick () {
         console.log('我是行编辑按钮');
      },
      rowClick (row, column) {
         console.log('点击了某一行');
      }
   },
   data () {
     return {
       tableData: [
         { date: '2016-05-02', name: '王小虎', province: '上海', city: '普陀区' },
         { date: '2016-05-04', name: '王小二', province: '北京', city: '朝阳区' }
       ]
     };
    }
 };
</script>

原因分析

编辑按钮的父元素是单元格,单元格父元素是行。所以编辑按钮在点击时,会产生“冒泡”。从而触发行点击事件。

解决办法

1.按钮是el-button标签,为点击事件加.native.stop ,即 @click.native.stop=“handleClick(scope.row)”

2.按钮通过render函数渲染实现,render函数中自带event事件,不用传参,不用写e,直接e.stopPropagation()就可以,当然,加上e也没毛病。

on:{
   click:e=>{
     e.stopPropagation();
    ....
}
posted @ 2020-09-24 16:59  Lemoncool  阅读(13154)  评论(0编辑  收藏  举报