1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > vue input 点击文本变输入框 失焦后变回文本 解决点击文本时自动获取焦点

vue input 点击文本变输入框 失焦后变回文本 解决点击文本时自动获取焦点

时间:2020-08-28 07:46:05

相关推荐

vue input 点击文本变输入框 失焦后变回文本 解决点击文本时自动获取焦点

最开始效果是不对的,点击一行单元格,虽然由文本变为输入框了,但是当点击第二行的输入框时,第一行并没有失焦,因为失焦事件加在了input上,当点击时input 并没有聚焦,所以当点击第二个时也没走失焦事件

原代码

<el-table:data="tableData"border:header-cell-style="{background:'#f5f7fa',color:'#909399'}"style="width: 100%"class="table-style"><el-table-column prop="date" label="日期" align="center"></el-table-column><el-table-column prop="name" label="姓名" align="center"><template slot-scope="scope"><spanv-if="!scope.row.cellNameVisible"@click="cellClick(scope.row, 'cellNameVisible')">{{ scope.row.name }}</span><el-inputv-if="scope.row.cellNameVisible"type="textarea":autosize="{ minRows: 1, maxRows: 9999}"v-model="scope.row.name"@blur="blurEvent(scope.row,'cellNameVisible')"></el-input></template></el-table-column><el-table-column prop="address" align="center" label="地址"></el-table-column></el-table>

// data中tableData: [{id: 1,date: '-05-02',name: '王小虎',address: '上海市普陀区金沙江路 1518 弄',cellNameVisible: false,}, {id: 2,date: '-05-04',name: '王小虎',address: '上海市普陀区金沙江路 1517 弄',cellNameVisible: false,}, {id: 3,date: '-05-01',name: '王小虎',address: '上海市普陀区金沙江路 1519 弄',cellNameVisible: false,}, {id: 4,date: '-05-03',name: '王小虎',address: '上海市普陀区金沙江路 1516 弄',cellNameVisible: false,}]

methods/*** 点击文本触发,显示input框,隐藏span标签*/cellClick(row, cellIndex) {this.$nextTick(() => {this.$refs.inputFocus.focus();});row.cellNameVisible = true;},/*** 输入框失去焦点触发*/blurEvent(row, cellIndex) {row.cellNameVisible = false;},

运行代码发现效果不对如第一张图所示还是没聚焦,开始确认是否是使用v-if导致的,换成v-show,还是不行,最后找百度,结合之前的代码,终于找到了原因,渲染组件需要时间,但是时间没有JS执行的快;所以获取不到。

方法一:加个指令 v-focus

<spanv-if="!scope.row.cellNameVisible"@click="cellClick(scope.row, 'cellNameVisible')">{{ scope.row.name }}</span><el-inputref="inputFocus"v-if="scope.row.cellNameVisible"type="textarea":autosize="{ minRows: 1, maxRows: 9999}"v-model="scope.row.name"@blur="blurEvent(scope.row,'cellNameVisible')"v-focus/>

/*** 点击文本触发,显示input框,隐藏span标签*/cellClick(row, cellIndex) {row.cellNameVisible = true;},/*** 输入框失去焦点触发*/blurEvent(row, cellIndex) {row.cellNameVisible = false;},

方法二: 使用setTimeout

data中加一个属性

timer: null,

/*** 输入框失去焦点触发*/blurEvent(row){row.cellNameVisible = false;},/*** 点击文本触发,显示input框,隐藏span标签*/cellEdit(row){if (this.timer) {clearTimeout(this.timer);}this.timer = setTimeout(() => {this.$refs.inputFocus.focus();}, 10);row.cellNameVisible = true;},

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。