user12009061
user12009061

Reputation:

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:

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?

Upvotes: 4

Views: 11831

Answers (3)

Satyam Pathak
Satyam Pathak

Reputation: 6922

You can have the $event reference to the saved method

  <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

Upvotes: 0

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

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 to add 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 inside the method trigger the focus programmatically :

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

Upvotes: 2

Mouradif
Mouradif

Reputation: 2704

Give a ref to your input :

<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();

Upvotes: 0

Related Questions