第一种
<input class="ModifyInput" ref="test" v-model="valueEdit" />
//获取焦点
1.this.$refs.test.focus()
2.this.$refs[·test·].focus()//模板字符串或引号
第二种 动态生成的input
<input class="ModifyInput"
:ref="`tableInput${i}-${index}`"
v-show="displayInputIndex === index && displayInputI === i"
v-model="valueEdit" />
//获取焦点
let refName = `tableInput${this.displayInputI}-${this.displayInputIndex}`
setTimeout(() => {
this.$refs[refName][0].focus() //获取焦点
this.$refs[refName][0].select() //选中文本
}, 200)
// this.$refs[refName]拿到的是一个数组~所以用下标【0】具体来控制获取焦点
//很奇怪 如果这种方式强制性写 this.$refs['tableInput0-1'].focus() 会报错.focus is not a function
//应该是dom加载问题
ps:
<input class="ModifyInput" :ref="`aaa`" v-model="valueEdit" /> //:ref 模板字符串
//js
let test = `aaa`
console.log(this.$refs[test])//确切的标签
this.$refs[test].focus()//能获取焦点
this.$refs['aaa'].focus()//也能获取焦点
另外
table表格输入框 enter或tab键 自动切换下一行
思路 通过一个行下标和列下标 切换
//displayInputIndex 行下标,displayInputI列下标
<input
class="ModifyInput"
:ref="`tableInput${i}-${index}`"
v-show="displayInputIndex === index && displayInputI === i"
v-model="valueEdit"
@blur="ModifyValue(i, index)"
@keydown="columInputKeydown($event, i, index)"
/>
//js
columInputKeydown(e, i, index) {
switch (e.code) {
case 'Tab':
case 'Enter':
case 'NumpadEnter':
console.log('键盘事件', e)
e.preventDefault() //组织事件并发
// 先把编辑值存起来,再计算要展示输入框的两个索引值
this.valueSave = Number(this.valueEdit)
// 1.最后一行,最后一列时,回到第一行第一列
// 2.最后一行时,行清零,列+1
// 3.最后一列时,列清零,行+1
// 4.其他情况,就列+1
if (i + 1 === this.ChooseLine.charValues.length && index + 1 ===this.ChooseColumn.charValues.length) {
this.displayInputI = 0
this.displayInputIndex = 0
} else if (index + 1 === this.ChooseColumn.charValues.length) { this.displayInputIndex = 0
this.displayInputI = i + 1
} else {
this.displayInputIndex = index + 1
}
// 根据拼接的ref属性名,找到指定input的DOM,执行聚焦、全选事件
let refName = `tableInput${this.displayInputI}-${this.displayInputIndex}` this.valueEdit = this.condition(this.displayInputI, this.displayInputIndex)
if (this.$refs[refName] && this.$refs[refName][0]) {
setTimeout(() => {
this.$refs[refName][0].focus()
this.$refs[refName][0].select()
}, 200)
}
break
default:
break
}
},