Home  >  Q&A  >  body text

How to trigger input focus event inside method in Vue.js?

I have an input that uses the following events:

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

How do I use this inside @focus="$event.target.select()" Event:

The above method copies the value. I need to trigger the above selection focus event when the user clicks copy How can this be done correctly?

P粉702946921P粉702946921370 days ago614

reply all(2)I'll reply

  • P粉441076405

    P粉4410764052023-10-30 14:42:46

    Provide a reference for your input:

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

    Then anywhere in the component script:

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

    reply
    0
  • P粉555696738

    P粉5556967382023-10-30 09:08:27

    Add saved method as focus event handler:

    @focus="saved"

    method:

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

    edit:

    Try adding ref to the input element

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

    Then trigger focus programmatically within the method:

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

    reply
    0
  • Cancelreply