Vue JS - injecting default value to custom radio group

365 просмотра

1 ответ

164 Репутация автора

So i tried to inject a default value to custom radio component that i wrote

Here's the code:

<div class="custom-radio-button">
  <div  v-for= "item in localValue">
    <input type="radio" :value="item.value" name=item.name @click=onSelected(item.value) >


  import Vue from 'vue'

  const name = 'CustomRadioButton'

  export default {
    componentName: name,

    props: [ 'name', 'value', 'isDefault', 'label'],

    data() {
      return { 
        localName: this.name,
        localValue: this.value
    methods: {
      onSelected (value) {
        this.$emit('clicked', value)

And here's how i called it:

<CustomRadioButton :value=RadioFieldData  @clicked="isRadioButtonSelection" isDefault='yellow'></CustomRadioButton>

And here's the Json Data that goes with it

  {label:'Fire', value:'red', name:'colour' },
  {label:'Sun', value:'yellow', name:'colour',isDefault:'yellow'},
  {label:'Water', value:'blue', name:'colour'}

My question is what is the best way to pass the value "yellow" to the radio buttons group?

Автор: Amy Lee Источник Размещён: 09.11.2017 12:09

Ответы (1)

1 плюс

106055 Репутация автора


Your issue is that props need to be represented in their kebab-case format when used in your template. To set isDefault to "yellow", you need to use


See https://vuejs.org/v2/guide/components.html#camelCase-vs-kebab-case

Once you're able to read that property correctly, you can use

:checked="item.value == isDefault"

Here's an example.

Vue.component('custom-radio-button', {
  template: `<div class="custom-radio-button">
  Default: {{isDefault}}
  <div v-for="item in value">
    <input type="radio" :value="item.value" name="item.name" @click="onSelected(item.value)" :checked="item.value == isDefault" />
  props: ['value', 'isDefault'],
  methods: {
    onSelected(value) {
      this.$emit('clicked', value)

new Vue({
  el: '#app',
  methods: {
    isRadioButtonSelection (val) {
      console.log('isRadioButtonSelection', val)
  data: {
    RadioFieldData: [{"label":"Fire","value":"red","name":"colour"},{"label":"Sun","value":"yellow","name":"colour","isDefault":"yellow"},{"label":"Water","value":"blue","name":"colour"}]
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<div id="app">
  <custom-radio-button :value="RadioFieldData" 

Автор: Phil Размещён: 09.11.2017 03:34
Вопросы из категории :