Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.JS custom radio button component requires clicking twice

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

like image 323
ierdna Avatar asked Mar 09 '17 15:03

ierdna


1 Answers

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.

  1. 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>

  2. Get rid of the val data property (since it isn't being used now).

  3. Change your update method to this.$emit('change', this.value); (you can just directly reference the value you've assigned this radio component).

like image 195
thanksd Avatar answered Oct 22 '22 06:10

thanksd