本文是參考前端大佬的代碼做了小的修改, 把冗余部分代碼調整了一下, 不用寫相同的函數了
參考自: https://blog.csdn.net/MengRui2333/article/details/103886630
1 template部分
<template> <div class="content-wrapper"> <div class="card-body"> <el-table height="600px" :data="tableData" border stripe style="width: 100%"> <el-table-column :show-overflow-tooltip="true" align="center" prop="enddate" label="第一列" width="250"> <template slot-scope="scope"> <div @dblclick="changeEnddate(scope.$index,'tag1', scope.row)" style="height: 40px;line-height: 40px;"> <span v-show="!scope.row.is_show_tag1">{{scope.row.tag1}}</span> <el-input :ref='"enddateinput"+"tag1"+"&"+scope.$index' @blur="switchShow(scope.$index,'tag1')" clearable @keyup.enter.native="$event.target.blur" v-show="scope.row.is_show_tag1" size="mini" v-model="scope.row.tag1"></el-input> </div> </template> </el-table-column> <el-table-column :show-overflow-tooltip="true" align="center" prop="enddate" label="第二列" width="250"> <template slot-scope="scope"> <div @dblclick="changeEnddate(scope.$index,'tag2', scope.row)" style="height: 40px;line-height: 40px;"> <span v-show="!scope.row.is_show_tag2">{{scope.row.tag2}}</span> <el-input :ref='"enddateinput"+"tag2"+"&"+scope.$index' @blur="switchShow(scope.$index,'tag2')" clearable @keyup.enter.native="$event.target.blur" v-show="scope.row.is_show_tag2" size="mini" v-model="scope.row.tag2"></el-input> </div> </template> </el-table-column> </el-table> </div> </div> </template>
2 script部分
<script> export default { name: "test2", data() { return { tableData: [{'tag1': '可修改的標簽1', 'tag2': '可修改的標簽2'}, {'tag1': '可修改的標簽3', 'tag2': '可修改的標簽4'}], }; }, methods: { // 切換input框的顯示狀態 switchShow(index, tag, tmp_this=this){ // 因為涉及到調用不同名稱的變量, 不清楚怎么寫, 只能先用switch case解決 switch (tag) { case "tag1": tmp_this.tableData[index].is_show_tag1 = !tmp_this.tableData[index].is_show_tag1; break; case "tag2": tmp_this.tableData[index].is_show_tag2 = !tmp_this.tableData[index].is_show_tag2; break; // ... } tmp_this.tableData = [...tmp_this.tableData];//因為我table綁定的表格數據是后接過來賦值的,所以需要這步操作,如果沒有1、2步驟這個可以不加。后面也一樣 }, // 顯示input框, 使光標焦點當前input框 changeEnddate(index, tag, rowdata){ this.switchShow(index, tag, this); // console.log('enddateinput' + index, typeof 'enddateinput' + index); // console.log(rowdata, typeof rowdata); setTimeout( ()=> { //定時器是為了避免沒有獲取到dom的情況報錯,所以象征性的給1毫秒讓他緩沖 this.$refs['enddateinput' + tag + '&' + index].focus() //el-input的autofocus失效,所以用這個方法。對應在template里的refs綁定值 }, 1) }, } } </script>
最終效果: 能實現雙擊某個單元格顯示input框進而編輯單元格內容, 光標挪出來輸入框隱藏, 顯示已修改的內容, 如圖 :
備注: el-table-column標簽就不要用 sortable 可排序屬性了, 因為一排序就打亂了數據行的index, 導致雙擊后打開的並不是當前單元格中的input框.