Search code examples
javascriptvue.jsvuejs2vue-componentbootstrap-vue

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?


Solution

  • 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();
         ...
        }
    }