需求:点击 ‘编辑’ 图标备注文本信息变成输入框可编辑,编辑后焦点离开发请求到后台修改数据;
效果图:
开始状态
点击后
修改以及修改后:
<el-table-column label="备注" align="left" width="200px">
<template slot-scope="scope">
<p class="font-editByFont">
{{ scope.row.remark }}
</p> <!-- 要修改的文本 -->
<i
class="el-icon-edit"
@click="editByFont(scope.row.id, scope.$index)"
></i> <!-- 编辑图标 -->
</template>
</el-table-column>
//编辑备注
editByFont(id, index) {
var oldhtml = document.getElementsByClassName('font-editByFont')[index]
.innerHTML
//如果已经双击过,内容已经存在input,不做任何操作
if (oldhtml.indexOf('type="text"') > 0) {
return
}
//创建新的input元素
var newobj = document.createElement('input')
//为新增元素添加类型
newobj.type = 'textarea'
//为新增元素添加value值
newobj.value = oldhtml
//为新增元素添加光标离开事件
newobj.onblur = function() {
//当触发时判断新增元素值是否为空,为空则不修改,并返回原有值
if (this.value && this.value.trim() !== '') {
document.getElementsByClassName('font-editByFont')[index].innerHTML =
this.value == oldhtml ? oldhtml : this.value
} else {
document.getElementsByClassName('font-editByFont')[
index
].innerHTML = oldhtml
}
//修改备注
let postData = {
id: id,
remark: document.getElementsByClassName('font-editByFont')[index]
.innerHTML
}
axios
.post('yourUrl', postData)
.then(() => {
this.$message({
message: '修改成功',
type: 'success'
})
})
.catch(err => {
this.$message.error(err)
})
}
//设置该标签的子节点为空
document.getElementsByClassName('font-editByFont')[index].innerHTML = ''
//添加该标签的子节点,input对象
document
.getElementsByClassName('font-editByFont')
[index].appendChild(newobj)
//设置选择文本的内容或设置光标位置(两个参数:start,end;start为开始位置,end为结束位置;如果开始位置和结束位置相同则就是光标位置)
newobj.setSelectionRange(0, oldhtml.length)
//设置获得光标
newobj.focus()
},
有个问题:就是添加焦点事件后,这里面调不了其他方法,,好像是异步,但在里面改变量后通过 vue 的监听 watch: {} 也监听不到,奇了个大怪,,,
上面的方法傻了吧唧,下面看下面的,同样的功能,写代码灵感 就很重要;
代码如下:
<el-table-column
label="备注"
v-if="orderStatusradio == 5"
align="left"
min-width="150px"
>
<template slot-scope="scope">
<p
v-if="!scope.row.editing"
class="remark-font"
@dblclick="toEditByFont(scope.row.oid)"
>
{{ scope.row.orderProcessRemark }}
<i
class="el-icon-edit"
@click="toEditByFont(scope.row.oid)"
></i>
</p>
<el-input
v-else
placeholder="备注信息"
type="textarea"
:autosize="{ minRows: 1, maxRows: 5 }"
v-model="scope.row.orderProcessRemark"
@blur="
editingByFont(scope.row.oid, scope.row.orderProcessRemark)
"
@keyup.enter.native="
editingByFont(scope.row.oid, scope.row.orderProcessRemark)
"
>
{{ scope.row.orderProcessRemark }}
</el-input>
</template>
</el-table-column>
toEditByFont(oid) {
this.tableData.forEach(item => {
if (item.oid == oid) {
item.editing = true
}
})
},
editingByFont(oid, orderProcessRemark) {
console.log('oid', oid)
console.log('orderProcessRemark', orderProcessRemark)
//调接口进行修改备注
this.tableData.forEach(item => {
if (item.oid == oid) {
item.editing = false
}
})
},
效果图: