需求

点击按钮后自动生成符合用户配置的四则运算题。

每次产生题后,自动聚焦在第一个输入框

用户在输入完答案,按下回车键,如果正确,则隐藏,并自动聚焦到下一个未隐藏的输入框

190189b6ab99

image.png

实现

Input 组件

{{item}}

@on-keydown.enter="submit" v-model="answer[index].user_result">

:ref="'input'+index" 是关键 用来后续引用组件

toggle_model(){

this.answer_model = !this.answer_model;

this.expressionsList = [];

if(this.answer_model){

this.generate_expressions();

this.$nextTick(()=>{

// this.$refs['input0'][0].$refs.input.focus();

this.$refs['input0'][0].focus();

})

}

},

this.generate_expressions(); 填充了expressionsList

this.$nextTick 里面的代码 让每次生成题第一个输入框都可以自动获得焦点

this.$refs['input0'][0].focus(); 中的focus 是Input组件提供的方法

点击回车键让下一个聚焦 则不需要使用 this.$nextTick ,找到第一个未被隐藏的索引,使用上述方法即可

上述答案是踩了很多坑之后发现的

使用自定义指令、深度监听属性、Input组件的autofocus、如何在列表渲染完成后执行方法、Input组件的foucs怎么用、是不是因为组件的复用导致autofocus在第一次后失效等等。

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐