Вопрос:

Vue JS - injecting default value to custom radio group

javascript input vue.js radio-button

365 просмотра

1 ответ

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

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

Here's the code:

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

</div>

<script>
  import Vue from 'vue'

  const name = 'CustomRadioButton'

  export default {
    name,
    componentName: name,

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


    data() {
      return { 
        localName: this.name,
        localValue: this.value
      }
    },
    methods: {
      onSelected (value) {
        this.$emit('clicked', value)
      }
    }
  }
</script>

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

RadioFieldData:[
  {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

is-default="yellow"

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" />
    <span>{{item.label}}</span>
  </div></div>`,
  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" 
                       @clicked="isRadioButtonSelection"
                       is-default="yellow">
  </custom-radio-button>
</div>

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