源网址:el-table点击单元格自动聚焦可编辑,且失去焦点即修改成功的实现方法_el-table focus_宝贝QY的博客-CSDN博客
实现过程
<el-table
:data="dataList"
border
v-loading="loadingFlag"
style="width: 100%;"
size="small"
@selection-change="selectChange"
>
<el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
<el-table-column type="index" align="center" label="序号" width="60"></el-table-column>
<el-table-column
align="center"
label="名称"
min-width="120"
>
<!--关键代码-->
<template slot-scope="scope">
<el-input v-if="scope.row.isSelected" v-model="scope.row.name" @focus="focusEvent(scope.row)" @blur="blurEvent(scope.row)" v-focus></el-input>
<p @click="cellClick(scope.row)" v-else>{{scope.row.name}}</p>
</template>
</el-table-column>
<el-table-column label="地址" prop="mac" align="center"></el-table-column>
<el-table-column label="类型" prop="type" align="center"></el-table-column>
<el-table-column label="组" prop="group" align="center"></el-table-column>
<el-table-column label="域" prop="zoom" align="center"></el-table-column>
<el-table-column label="创建时间" prop="time" align="center"></el-table-column>
</el-table>
export default {
data () {
return {
dataList: [],
loadingFlag: true
}
},
components: {
PageTitle
},
directives: {
focus: {
inserted: function (el) {
el.querySelector('input').focus()
}
}
},
created () {
this.getList()
},
methods: {
getList () {
this.$http.get('/list').then(res => {
if (res.status === 200) {
this.loadingFlag = false
this.dataList = res.data.map(item => {
return {...item, isSelected: false}
})
console.log(this.dataList)
}
})
},
selectChange (e) {
console.log(e)
},
focusEvent (row) {
row.oldName = row.name
},
blurEvent (row) {
row.isSelected = !row.isSelected
if (row.name !== row.oldName) {
// 。。。此处代码省略(调用修改名称接口)
this.$message({
message: '修改成功',
type: 'success',
duration: 1000
})
}
},
cellClick (row) {
row.isSelected = !row.isSelected
}
}
}
内容讲解
methods
中getList
方法在拿到后台数据后给数组对象每一项中添加了同一个属性isSelected
,即:-
this.dataList = res.data.map(item => { return {...item, isSelected: false} })
- 有了
isSelected
属性后我们可以控制每一项名称的<el-input>
和<p>
标签的显示隐藏,从而来实现点击单元格即自动聚焦修改名称 -
<template slot-scope="scope"> <el-input v-if="scope.row.isSelected" v-model="scope.row.name" @focus="focusEvent(scope.row)" @blur="blurEvent(scope.row)" v-focus></el-input> <p @click="cellClick(scope.row)" v-else>{{scope.row.name}}</p> </template>
focusEvent
方法是为了记录用户聚焦该行前,该行的name
值:-
focusEvent (row) { row.oldName = row.name },
- 失去焦点时,比较
oldName
和name
是否相同 -
blurEvent (row) { // 目的是为了让<el-input>标签隐藏 row.isSelected = !row.isSelected if (row.name !== row.oldName) { // 。。。此处代码省略(调用修改名称接口) this.$message({ message: '修改成功', type: 'success', duration: 1000 }) } },
- 接下来要讲为什么要用自定义指令
v-focus
,当给<el-input>
标签添加autofocus
发现无效,然后看到网上提供的思路遂使用vue
框架提供的directives
: -
directives: { focus: { inserted: function (el) { el.querySelector('input').focus() } } },