I have a custom radio button component with the following HTML markup:
<div id="app">
{{message}} - {{sex}}
<radio value="m" v-model="sex" name="sex">Male</radio>
<radio value="f" v-model="sex" name="sex">Female</radio>
</div>
The component (and app) are defined as follows:
Vue.component('radio', {
model : {
prop:'checked',
event:'change'
},
props : {
value:null,
name:String
},
data : () => ({
val:''
}),
methods : {
update (e) {
this.$emit('change',e.target.value);
}
},
template:'<div><input :value="value" :name="name" type="radio" v-model="val" @change="update"><slot></slot></div>'
})
var app = new Vue({
el: '#app',
data: {
message: 'selected:',
sex:''
}
})
jsFiddle
It switches the radio buttons correctly (for the most part).
Problem: in order to do so I have to click Male radio button twice. I'd like to be able to only click it once to toggle them. Perhaps I'm not using the model
attribute described here correctly?
I saw this question, but it uses older Vue (which doesn't have model
attribute) and I don't want to have to capture @change on the parent (the entire idea behind the separate component is to abstract as much logic as possible)
update: For anyone interested here is the solution thanks to @thanksd
Not exactly sure what's causing that bug, but I see that you're doing some unnecessary data-binding that are apparently causing the issue.
Change the radio
component template to this (don't need to pass a value or bind a v-model):
<div><input :name="name" type="radio" @change="update"><slot></slot></div>
Get rid of the val
data property (since it isn't being used now).
Change your update method to this.$emit('change', this.value);
(you can just directly reference the value you've assigned this radio
component).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With