简体   繁体   English

如何在 Vue.js 的方法内触发输入焦点事件?

[英]How to trigger the input focus event inside a method in Vue.js?

I have an input for which is using the following event:我有一个使用以下事件的输入:

 <b-nput
            class="input"
            id="link"
            v-model="link"
            placeholder="link"
            @focus="$event.target.select()"
          ></b-input>

How can I use this @focus="$event.target.select()" event inside:我如何在里面使用这个@focus="$event.target.select()"事件:

The above method copies the value.上述方法复制该值。 I need to trigger the above select focus event when the user clicks copy How can be it achieved correctly?我需要在用户点击复制时触发上面的select焦点事件如何才能正确实现呢?

Add saved method as focus event handler:添加saved的方法作为焦点事件处理程序:

@focus="saved"

method:方法:

methods: {
  saved(event){ //the event is passed automatically as parameter
     event.target.select()
  }
}

Edit:编辑:

Try to add ref to the input element尝试将ref添加到输入元素

 <b-input
          ref="input"
            class="input"
            id="link"
            v-model="link"
            placeholder="link"
         
            @focus="$event.target.select()"
          ></b-input>

then inside the method trigger the focus programmatically:然后在方法内部以编程方式触发焦点:

 methods: {
      async copy(s) {
      await navigator.clipboard.writeText(s) 
      this.$refs.input.focus();
     ...
    }
}  

You can have the $event reference to the saved method您可以将$event引用到已saved的方法

  <b-nput
        class="input"
        id="link"
        v-model="link"
        placeholder="link"
        @focus="saved"
      ></b-input>


methods: {
  saved(event){
    console.log(event)
  }
}

ref - https://v2.vuejs.org/v2/guide/events.html参考 - https://v2.vuejs.org/v2/guide/events.html

Give a ref to your input:为您的输入提供ref

<b-input
            class="input"
            id="link"
            v-model="link"
            placeholder="link"
            ref="theInput"
          ></b-input>

then anywhere in your Component script:然后在您的组件脚本中的任何地方:

this.$refs['theInput'].focus();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM