Home > other >  How to select text inside input when the input get mounted (Vue3 )
How to select text inside input when the input get mounted (Vue3 )

Time:12-19

I have this form that I created, basically what its doing is creating a new input with a random value each time I click on ADD_INPUT button. the thing I want is each time I create a new INPUT with random value the value get selected. Sorry for my very bad English.

I've tried creating a new customized directive like this :

directives: {
    focusInput: {
      // directive definition
      mounted(el) {
        el.select()
      }
    }
  }, 

but it breaks idy

CodePudding user response:

Hoy can use select()

new Vue({
    el : '#app',
  data : {
   text: 'some text'
  },
  methods : {
    select() {
      this.$refs.input.select();
    },
  },
  mounted() {
    this.select()
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button @click="select">ADD_INPUT</button>
  <input type="text" v-model="text" ref="input">
</div>

Composition API

setup() {
    const input = ref(null)

    function select() {
      input.value.select()
    }

    return {
      input,
      select
    }
  }
  • Related