Maiken Madsen
Maiken Madsen

Reputation: 651

How to onFocus on v-text-field and change value to empty

I want to set the value to empty on a v-text-field when onFocus.

I have tried the onFocus attribute but nothing happen. I want to clear the value on focus and not using the clearable button from vuetify.

<v-text-field type="number" value="0"></v-text-field>

Any suggestions on how to do that?

Upvotes: 1

Views: 9158

Answers (3)

Yernar.T
Yernar.T

Reputation: 84

I had the same problem and I solved it!

I'm using Vue2.x (not 2.7), Vuetify 2.x

<v-text-field @blur @focus />

https://v2.vuetifyjs.com/en/api/v-input/#events, As described in the documentation, the blur and focus events of the v-text-field component are not thrown.


My solution:

  1. Give him a ref attribute. <v-text-field ref="textField" />
  2. define event handler
methods: {
       onFocus() {
           this.$emit('focus');
       },

       onBlur() {
           this.$emit('blur');
       }
   }
  1. use event listener
mounted() {
        const input = this.$refs.textField.$el.querySelector('input');
        input.addEventListener('focus', this.onFocus);
        input.addEventListener('blur', this.onBlur);
    },

    beforeDestroy() {
        const input = this.$refs.textField.$el.querySelector('input');
        input.removeEventListener('focus', this.onFocus);
        input.removeEventListener('blur', this.onBlur);
    }

Upvotes: 0

Pierre Said
Pierre Said

Reputation: 3830

You can use the @focus event to trigger a method. Here is an example with an input. I used v-model

more info on Vue.js events.

Vue.config.devtools = false;
Vue.config.productionTip = false;

var app = new Vue({
  el: '#app',
  data: {
    value: 'test'
  },
  methods: {
    onFocus() {
      this.value = '';
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input v-model="value" @focus="onFocus" />
</div>

Upvotes: 1

isebarn
isebarn

Reputation: 3950

Can you try

<v-text-field type="number" value="0" @focus="someMethod()"></v-text-field>

If you check the vuetify docs

v-text-field

you will see that there is a tab events on the right page margin, along with slots and props

Upvotes: 0

Related Questions