Vue学习笔记之获取光标

如下展示了两种获取光标的形式 focus():

1、页面加载完成之后,自动获取光标到 input输入框。

       思路:

    directives自定义函数 
inserted在dom树绘制后调用

2、通过点击button 出发事件,使光标定位到input 输入框。

       思路:

              $refs 操作DOM元素

<template>
  <div class="homediv">
  <van-nav-bar title="标题" />
  点击获得光标<input type="text" ref="inpclick">
  <button @click="getgb" ref="getgb">get</button><br/>
   加载完成获得光标<input type="text"  v-focus="true">
  </div>
</template>

<script>
export default {
    methods:{
      //点击获得光标
      getgb(){
        console.log(this.$refs);
        this.$refs.inpclick.focus()
      }},
      //页面加载完成之后,自动获得光标   
     directives: {    
        focus: {           
            inserted: function (el, {value}) {             
                console.log(el,{value})            
                if (value) {                   
                    el.focus();            
                }          
            }      
        }  
    }
}
</script>

<style>
     .homediv .van-nav-bar__content{
     background-color:rgb(55, 140, 236);
     color:white ;
}
 
</style>

 

posted @ 2022-04-11 13:57  甜酒1996  阅读(1830)  评论(0)    收藏  举报