main.js中全局注册指令:
// 注册一个全局自定义指令 `v-focus`
Vue.directive('focus', {
// 当被绑定的元素插入到 DOM 中时……
inserted: function (el) {
// 聚焦元素
// el.focus()
el.querySelector('input').focus()
}
})
实现代码:
<!--main-->
<template>
<div class="main">
<el-table
:data="tableData"
style="width: 100%"
@cell-dblclick="tabClick"
:row-class-name="tableRowClassName"
:cell-class-name="tableCellClassName"
>
<el-table-column prop="date" label="日期" width="180"> </el-table-column>
<el-table-column prop="name" label="姓名" width="180"> </el-table-column>
<el-table-column label="地址" show-overflow-tooltip>
<template slot-scope="scope">
<div
v-if="
scope.row.index === clickRowIndex &&
scope.column.index === clickCellIndex
"
>
<el-input
v-model="scope.row.address"
@blur="inputBlur"
size="mini"
v-focus
/>
</div>
<div v-else>{{ scope.row.address }}</div>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [
{
date: "2016-05-02",
name: "王小虎",
address: "上海市普陀区金沙江路 1518 弄",
},
{
date: "2016-05-04",
name: "王小虎",
address: "上海市普陀区金沙江路 1517 弄",
},
{
date: "2016-05-01",
name: "王小虎",
address: "上海市普陀区金沙江路 1519 弄",
},
],
clickRowIndex: null, // 当前点击的行索引
clickCellIndex: null, // 当前点击的列索引
tabClickLabel: "", // 当前点击的列名
};
},
props: {},
created() {},
mounted() {},
computed: {},
methods: {
// 控制input显示 row 当前行 column 当前列
tabClick(row, column, cell, event) {
console.log("row:", row);
console.log("column:", column);
console.log("column.index:", column.index);
console.log("column.label:", column.label);
this.clickRowIndex = row.index;
this.clickCellIndex = column.index;
this.tabClickLabel = column.label;
},
// 失去焦点初始化
inputBlur(row, event, column) {
this.clickRowIndex = null;
this.clickCellIndex = null;
this.tabClickLabel = "";
console.log("this.tableData:", this.tableData);
},
// 把每一行的索引放进row
tableRowClassName({ row, rowIndex }) {
row.index = rowIndex;
},
// 把每一列的索引放进column
tableCellClassName({ column, columnIndex }) {
column.index = columnIndex;
},
},
};
</script>