使用无线电创建自己的Vue2组件,如何更改值

时间:2018-01-18 19:17:08

标签: javascript binding vuejs2 vue-component

我尝试使用单选按钮创建自定义组件,但只使用标签值来获取工作方式,而不是价值道具。

示例,而是标签1,2,3 =>显示标签"所有","私人","专业"得到价值1,2,3

代码段不起作用,external link代码框工作正常。



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() {
          this.$emit("change", this.label)
        }
      }
});


Vue.component('example-form', {
  template: `
     <div class="row">
    <div class="col-lg-1 col-centered">
      Test for component with radio buttons
    </div>
    <div>
      <radio-button name="options" label="1" :value="selectedAdvertiser" @change="changeAdvertiser"/>
      <radio-button name="options" label="2" :value="selectedAdvertiser" @change="changeAdvertiser"/>
      <radio-button name="options" label="3" :value="selectedAdvertiser" @change="changeAdvertiser"/>
      <hr>
      <div class="result">
        Radio button selection: {{selectedAdvertiser}}
      </div>
    </div>
  </div>
  `,
  data: function() {
    return {
      selectAdvertiser: "1"
    }
  },
  methods: {
    changeAdvertiser: function(newValue) {
      this.selectedAdvertiser = newValue
    }
  }
});

var App = new Vue({
  el: '#my-app"
  template: `<example-form></example-form>`
});
&#13;
<script src="https://unpkg.com/vue"></script>
<body>
    <div id="my-app"></div>
</body>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

问题在于你使用价值的方式。

在DropDownComponent.vue中:

  <radio-button name="options" label="1" :value="selectedAdvertiser" @change="changeAdvertiser"/>
  <radio-button name="options" label="2" :value="selectedAdvertiser" @change="changeAdvertiser"/>
  <radio-button name="options" label="3" :value="selectedAdvertiser" @change="changeAdvertiser"/>

所有3个单选按钮的值都相同,但应该选择该单选按钮选项的唯一值。

例如:

  <radio-button name="options" label="1" value="One" @change="changeAdvertiser"/>
  <radio-button name="options" label="2" value="Two" @change="changeAdvertiser"/>
  <radio-button name="options" label="3" value="Three" @change="changeAdvertiser"/>

另外,如果您发出input而不是change,则DropDownComponent可以按以下方式访问该值:

  <radio-button name="options" label="1" value="One" v-model="selectedAdvertiser"/>
  <radio-button name="options" label="2" value="Two" v-model="selectedAdvertiser"/>
  <radio-button name="options" label="3" value="Three" v-model="selectedAdvertiser"/>