6

I have a vue component that extends a native radio input with extra markup and styling, the intent being that it can be used throughout the app as a stand-in for a regular radio:

<div class="radios">
  <radio-input name="radioInput" value="one" v-model="options.firstOption">
  <radio-input name="radioInput" value="two" v-model="options.firstOption">
  <radio-input name="radioInput" value="three" v-model="options.firstOption">
</div>

I've been following the approach suggested here (jsfiddle here) but am wanting to add the ability for the component to accept a v-model attribute, which this example doesn't do.

Here's my .vue component file so far:

<template>
  <span class="radio-control">
    <input
      class="input-bool"
      type="radio"
      :name="name"
      :value="value"
      v-model="radioButtonValue">
  </span>
</template>

<script>
  export default {
    model: {
      prop: 'checked',
    },
    props: {
      name: String,
      value: String,
      checked: String
    },
    computed: {
      radioButtonValue: {
        get: function() {
          return this.checked;
        },
        set: function() {
          this.$emit('input', this.value);
        }
      }
    },
  };
</script>

All good, works great on change, the model updates. The issue is that the the radio's checked attribute is not applied when the component renders, so if someone hits the page, all radios show as blank until there's a change event.

Vue's docs explicitly state that "v-model will ignore the initial value, checked or selected attributes found on any form elements. It will always treat the Vue instance data as the source of truth." Adding it doesn't make a difference, as expected. But I'm having difficulty getting the native checked attribute to be present radio buttons at render.

3
  • What is options.firstOption when the page first renders? Commented May 18, 2017 at 1:28
  • @BertEvans one of either one, two, or three. Commented May 18, 2017 at 2:49
  • 1
    I took your exact code and made this pen. If I give it a starting value, the radio button is selected. codepen.io/Kradek/pen/PmderJ?editors=1010 Commented May 18, 2017 at 2:52

1 Answer 1

2

Not a vue.js issue at all, @bertEvans was correct in that the code I posted is working as it should. The problem was that I had a separate set of radio inputs further up on the page with the same name="" attribute. Folks, if your radio groups aren't behaving as expected, make sure each group has a unique name!

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.