Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuejs shared radio component not checked on render

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.

like image 579
essmahr Avatar asked May 17 '17 22:05

essmahr


1 Answers

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!

like image 175
essmahr Avatar answered Oct 15 '22 23:10

essmahr