美文网首页
vue input 通过js获取焦点

vue input 通过js获取焦点

作者: 毛豆豆豆豆子 | 来源:发表于2019-02-10 12:50 被阅读0次

主要讲$nextTick的用法, 既dom渲染完成执行的回调

实现的效果:当点击调价按钮的时候获取焦点
当点击调价按钮的时候获取焦点

html代码

<tr class="table-row" v-for=" (item,index) in tableData">
            <td v-show="item.show"><input type="number" ref="input" v-model="item.oldPrice" /></td>
            <td v-show="!item.show">{{item.price|fmtMoney}} </td>
            <td style="text-align:right">
                <i-button @click="editItem(item,index)" type="primary" size="small">{{item.show==1?"确定":"调价"}}</i-button>
            </td>
</tr>

js代码

methods:{
      editItem:function(item,index){
        // 控制显示或者隐藏input
          if(item.show == 1){
              this.$set(item,'show', 0);
            }else{
               this.$set(item,'show', 1);
                // 获取焦点
                // 错误代码
               this.$refs.input[index].focus();
                // 正确代码
                this.$nextTick(function(){
                        this.$refs.input[index].focus();
                })
            }
           
      }
}
  1. 给input设置ref
  2. 通过this.$refs获取dom
  3. 给dom设置焦点focus()

Tips: 设置对象属性时需要用$set否则dom不会重新渲染

Tips: focus()在dom渲染之前执行是无效的(显示但不会获取焦点),所以的用$nextTick,

相关文章

网友评论

      本文标题:vue input 通过js获取焦点

      本文链接:https://www.haomeiwen.com/subject/gywteqtx.html