Vue form component with custom radio button component

by Mani Jagadeesan

HTML

<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<body>
    <div id="my-app"></div>
</body>

CSS

body {
  margin: 20px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
label.radio {
  margin-right: 20px;
}
.result {
  margin-top: 15px;
  border-top: 1px solid #DDD;
  padding-top: 15px;
}

JavaScript

Vue.component('radio-button', {
    props: ['name', 'label', 'value'],
    template: `
    <label class="radio">
        <input type="radio" :value="label" :name="name" v-model="radioButtonValue">
        <span>{{ label }}</span>
    </label>
    `,
    computed: {
        radioButtonValue: {
            get: function() {
                return this.value
            },
            set: function() {
                // Communicate the change to parent component so that selectedValue can be updated
                this.$emit("change", this.label)
            }
        }
    }
});

Vue.component('example-form', {
    template: `
        <div>
            <radio-button name="options" label="1" :value="selectedValue" @change="changeValue"/>
            <radio-button name="options" label="2" :value="selectedValue" @change="changeValue"/>
            <radio-button name="options" label="3" :value="selectedValue" @change="changeValue"/>
            <div class="result">
                Radio button selection: {{selectedValue}}
            </div>
        </div>
    `,
    data: function() {
        return {
            selectedValue: "1"
        };
    },
    methods: {
        changeValue: function(newValue) {
            this.selectedValue = newValue;
        }
    }
});

new Vue({
    el: '#my-app',
    template: `<example-form></example-form>`
});