Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js 3 use autofocus on input with ref inside a method

I worked with Vue2, but I recently try Vue 3.

I have simple problem:

 <input ref="myinput" />
 <button @click="submitData" />

I want to set "focus" on "myinput", inside function "submitData". In Vue 2 it is simple (this.$refs ...), but in Vue 3, they made it complicated. I saw example with "setup", but is no use for me + I think you can only access "value" from element.

Is there any way to execute "focus" on on element inside methods?

like image 806
Ashko Avatar asked Nov 10 '20 17:11

Ashko


3 Answers

You are still able to do the same thing using Vue 3, but if you work with composition api there's some difference :

Options API :

const {
  createApp
} = Vue;
const App = {

  data() {
    return {

    }
  },
  methods: {
    submitData() {
      this.$refs.myinput.focus()
    }
  },
  mounted() {

  }
}
const app = createApp(App)
app.mount('#app')
<script src="https://unpkg.com/[email protected]/dist/vue.global.prod.js"></script>

<div id="app">
  Vue 3 app
  <input ref="myinput" />
  <button @click="submitData">
  Submit
  </button>
</div>

composition API:

const {
  createApp,
  ref,
  onMounted,

} = Vue;
const App = {

  setup() {
    const myinput = ref(null)

    function submitData() {
      myinput.value.focus()
    }

    return {
      myinput,
      submitData
    }
  }
}
const app = createApp(App)
app.mount('#app')
<script src="https://unpkg.com/[email protected]/dist/vue.global.prod.js"></script>

<div id="app">
  Vue 3 app
  <input ref="myinput" />
  <button @click="submitData">
  Submit
  </button>
</div>
like image 125
Boussadjra Brahim Avatar answered Oct 22 '22 15:10

Boussadjra Brahim


In case someone comes to this question looking for a way to set the autofocus of a specific element in Vue3, you can achieve it using a Vue Custom Directive

const { createApp, onMounted } = Vue;

const app = createApp({})

// Register a global custom directive called `v-focus`
app.directive('focus', {
  // When the bound element is mounted into the DOM...
  mounted(el) {
    // Focus the element
    el.focus()
  }
})

app.mount('#app')
<script src="https://unpkg.com/vue@next"></script>

<div id="app">
    <input />
    <input v-focus />
    <input />
</div>
like image 44
webcu Avatar answered Oct 22 '22 15:10

webcu


Easiest answer I found is missing here

<input type="text" autofocus />
like image 37
Akif Avatar answered Oct 22 '22 15:10

Akif