[youzan/vant]请教一下,如何使van-field得到焦点

2024-05-22 105 views
8

<van-field v-model="cardNo"
id="cardNo"
ref="cardNo"
type="number" icon="clear" placeholder="请输入支持银行卡号" required @click-icon="cardNo = ''"

js如下:

      if(this.cardNo.length<8){
            Dialog.alert({message:"错误的银行卡号."}).then(()=>{                     
                 //document.querySelector("#cardNo").focus();
                 //this.$refs['cardNo'].focus()
                 //我试图在这里让文本框有焦点,但以上两个都不行。
            });
            return;
        }

在不使用Vue.directive和修改vant源码的情况下.

同时想让文档框的maxlength等原生属性能起作用吗?

回答

0

@yurizhang 文档中有说明,Filed 默认支持 Input 标签所有的原生属性,比如 maxlength、placeholder、readonly 等 自动获取焦点可以用原生的 autofocus 属性,不过在 iOS 下是无效的,iOS 禁止输入框自动获取焦点,只能在点击事件中去 focus

https://www.youzanyun.com/zanui/vant#/zh-CN/component/field

9
  1. 刚我试了一下,不好意思,因为我是银行卡号,type=number所以 maxlength是不生效的。 type="text"时 maxlength才起作用。
  2. 焦点那个我是想通过编程控制, 比如银行卡号输错了,让用户文本框直接得到焦点。

谢谢你的快速回应~~

2

客气~

编程控制的话可以尝试下面的代码

const input = this.$refs['cardNo'].querySelector('input');
input.focus();
2

const input = this.$refs['cardNo'].querySelector.$el('input'); input.focus();

9

楼上那个获取到是组件,得在进一层$el

9

楼上的不完全对,完整的是这样:

const input = this.$refs['cardNo'].$el.querySelector('input')
input.foucs()
4
input.foucs()

focus