8

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

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.