user9945420
user9945420

Reputation:

toggle between input and change event by passing in boolean property

I have a basic textfield that fires the input event whenever the amount of characters change.

A basic example would be this textfield

        <v-text-field
          :value="value"
          label="Textfield"
          @input="updateValue"
        ></v-text-field>

with this Vue instance

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data(){
    return {
      value: 'abc',
    };
  },
  methods: {
    updateValue(){
      this.value = updateValue;
    }
  }
})

You can see a demo here

https://codepen.io/anon/pen/zgZWrG?editors=1010

The input event gets fired whenever the user is typing. I want to provide an option (boolean property like 'fireInputOnEachInput') and if this is false the textfield should use the change instead of input event.

A possible solution would be to use an if statement

<v-text-field
  v-if="fireInputOnEachInput"
  :value="value"
  label="Textfield"
  @input="updateValue"
></v-text-field>

<v-text-field
  v-else
  :value="value"
  label="Textfield"
  @change="updateValue"
></v-text-field>

but maybe there is a way to switch between the events only?

Upvotes: 1

Views: 409

Answers (1)

skirtle
skirtle

Reputation: 29112

There is direct support for using a dynamic event name. In your template:

<v-text-field
  :value="value"
  label="Textfield"
  @[eventName]="updateValue"
></v-text-field>

Then add a computed property:

eventName () {
  return this.fireInputOnEachInput ? 'input' : 'change'
}

Note that as HTML attribute names cannot contain spaces it's tricky to write this inline. You can find more on this in the original RFC.

There are various alternatives, such as this:

<v-text-field
  :value="value"
  label="Textfield"
  v-on="{[fireInputOnEachInput ? 'input' : 'change']: updateValue}"
></v-text-field>

In this case the square brackets are just an ES6 computed property name, see here, not to be confused with Vue computed properties which are a totally different thing.

See https://v2.vuejs.org/v2/api/#v-on for more on the various forms of v-on/@ syntax.

Upvotes: 1

Related Questions