前言
在开发表格中经常会有这样一个需求,点击单元的文本自动切换为输入框
看起来是个很简单的功能,输入框和文本框切换用用v-show或v-if,自动聚焦用autofocus属性
但是在实际开发后,会发现在文本在第二次切换为输入框后又无法自动聚焦了…
1、autofocus(自动聚焦)属性
- autofocus属性是布尔属性。
- 如果存在,它指定元素应在页面加载时自动获得焦点。
- 常用于input、select、button、textarea元素上
若两个元素都有autofocus,则采用至上而下方式,最上面的那个聚焦
2、问题以及解决办法
我们来实现一下这个需求:要求点击文字,显示输入框并自动聚焦到输入框上,输入框失去焦点时显示文字
思路:输入框和文本框切换用用v-show或v-if,自动聚焦用autofocus属性
没有自动聚焦
通过百度查询,可以得知autofocus属性只有在页面加载时才会设置,而想实现切换后自动获取聚焦无法用autofocus实现
解决方法:
自定义获取焦点的事件,每次插入或者更新的时候都自动聚焦
点击文字实现,切换输入框并自动聚焦到输入框内
遇到的小问题
在实际写的过程中遇到了一个小问题,v-focus放到v-show之前,自定义指令v-focus不起作用,写到v-show之后就可以了
去百度了一下 ,自定义指令和v-show的优先级是一样的
,排除是优先级引起的可能
另一种情况可能就是 v-show与自定义指令v-focus冲突
,v-show用来控制元素的显示隐藏,v-focus聚焦到元素上的前提是元素要存在。在两者优先级一样的情况下,如果v-focus先渲染,这时候元素还没有显示就无法聚焦,等再执行v-show显示元素的时候 v-focus已经执行完成;如果是v-show先执行,元素显示,再执行v-focus就能实现自动聚焦了
有其他的解决方案欢迎评论…