重命名输入框光标控制(vue)

使用工具为ts,vue-class-component

1. 光标基本操作

blur:使输入框失去焦点

focus:使输入框获得焦点

<template>
    <button @click='_rename' />
    <a-input v-show='ifRename' ref='myInput' />
</template>
import { Vue } from 'vue-class-component';
<script lang='ts'>
    export class MyInput extends Vue {
        ifRename = false;        

        private _blur() {
            this.$refs.myInput.blur()
        }

        private _focus() {
            this.$refs.myInput.focus()
        }

        
    }
</script>

2. 重命名操作

流程:点击button -> input显示 -> input获得焦点

<template>
    <button @click='_rename' />
    <a-input v-show='ifRename' ref='myInput' />
</template>
import { Vue } from 'vue-class-component';
<script lang='ts'>
    export class MyInput extends Vue {
        ifRename = false;        
        
        private _rename() {
            this.ifRename = true;
            (this.$refs.myInput as HTMLInputElement).focus()
        }
        
    }
</script>

问题:写完后发现input并没有按照预想获得焦点

分析:在运行完 this.ifRename = true 时,vue并不会立刻渲染更新,因此实际流程变成了: 点击button -> input获得焦点 -> input显示。

方案:解决方法思路为等vue渲染出input后再执行focus,vue的this.$nextTick(callback)在这里可以用到。nextTick会在下次DOM更新结束后执行括号内的回调。代码如下。

<template>
    <button @click='_rename' />
    <a-input v-show='ifRename' ref='myInput' />
</template>
import { Vue } from 'vue-class-component';
<script lang='ts'>
    export class MyInput extends Vue {
        ifRename = false;        
        
        private _rename() {
            this.ifRename = true;
            this.$nextTick(() => {
                (this.$refs.renameInput as HTMLInputElement).focus();
            });
        }
        
    }
</script>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值