Andriy Yushko
Andriy Yushko

Reputation: 415

How to make preventDefault for change on Element UI radio group

I'm using Element UI radio button group and I want to use preventDefault() when trigering change event:

<el-radio-group @change="changeHandler" v-model="radio1">
   <el-radio-button label="New York"></el-radio-button>
   <el-radio-button label="Washington"></el-radio-button>
   <el-radio-button label="Los Angeles"></el-radio-button>
   <el-radio-button label="Chicago"></el-radio-button>
</el-radio-group>

Script:

methods: {
  changeHandler(value, e) { 
    // e is undefined
    // here should be preventDefault
  }
}

I tried set second parameter to change function, but it is undefined.

Upvotes: 2

Views: 5303

Answers (2)

AVJT82
AVJT82

Reputation: 73357

Element UI works a bit differently. @change just returns the value chosen, nothing else. We need to use native to access the Event object. But @change.native won't work, as the change has already happened (if you want to actually prevent the change). As a side note, I would use disabled attribute instead (like presented in documentation). In my opinion for the UX it's weird that a user cannot choose a radio button, but putting that aside.... Use @click.native instead if you want to prevent a choice:

@click.native="changeHandler"

Then you have access to the Event object:

changeHandler(e) { 
  console.log(e.target.value)
  if(e.target.value == "Washington") {
    e.preventDefault();
  } 
}

CODEPEN

Upvotes: 6

turbopasi
turbopasi

Reputation: 3605

You're having the parameters in the method wrong. The are 2 ways this can go using the @change event handler:

A

defining a change handler without arguments, like

<el-radio-group @change="changeHandler" v-model="radio1" ></el-radio-group>

changeHandler(e) {
   // e will be the Event object
   console.log(e)
}

B

defining a change handler with arguments, put in $event to still include the event object

<el-radio-group @change="changeHandler($event, 'string')" v-model="radio1" ></el-radio-group>

changeHandler(e, value) {
   // e will be the Event object
   console.log(e);
   
   // value will be 'string'
   console.log(value);
}

Upvotes: 0

Related Questions