Vue JS - 向自定义无线电组注入默认值

时间:2017-11-09 00:09:31

标签: javascript input vue.js radio-button

所以我试图将默认值注入我写的自定义无线电组件

以下是代码:

<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>

以下是我的称呼方式:

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

这里有Json Data和它一起

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

我的问题是传递价值的最佳方式是什么?黄色&#34;到单选按钮组?

1 个答案:

答案 0 :(得分:1)

您的问题是道具需要在模板中使用时以 kebab-case 格式表示。要将isDefault设置为“黄色”,您需要使用

is-default="yellow"

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

一旦您能够正确阅读该属性,就可以使用

:checked="item.value == isDefault"

这是一个例子。

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>