需求簡述
表格用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(); .... }
