Vue get+set cursor position cursor position select input box text

Version: vue2 and vant2
use ref and refs to obtain dom in vue. In the vant framework, van − field is an input box component. It does not support the method set Selection Range ( ) to directly set the cursor, so it is obtained through this.refs For dom, van-field is an input box component in the vant framework. It does not support the method setSelectionRange() to directly set the cursor, so use this.ref s obtains do m , in v an t frame v an _f i e l d is an input box component, it does not support the method of directly setting the cursor se tS e l ec t i o n R an g e ( ) , so it is obtained through t hi s . refs.be.$refs.input Input this native dom, and then use it to set the cursor:

<van-field label="邮 箱" v-model.trim="buyerEmail" ref="be" placeholder="电子邮箱" clearable></van-field>

<script>
export default {
    
    
methods: {
    
    
  //我这里实现的是点击按钮自动在输入框后面加上@qq.com
  fillEmail(a){
    
    
    let em = this.buyerEmail ? this.buyerEmail : '';
    this.buyerEmail = em + a;
    let d = this.$refs.be.$refs.input; //获取dom
    this.$refs.be.focus();//设置焦点
    this.$nextTick(() => {
    
     //必需
    	//setSelectionRange两个参数是光标的起、止位置
    	//设置一样就是闪烁光标,不一样就是选择文本
    	//这里我是选择@前的内容
        d.setSelectionRange(0, this.buyerEmail.indexOf('@')); 
        console.log(d.selectionStart) //获取光标起始位置
        console.log(d.selectionEnd) //获取光标结束位置
    })
  },
}
}
<script>

Guess you like

Origin blog.csdn.net/jeesr/article/details/129278578