【问题标题】:Vue.js - cannot set radio button by defaultVue.js - 默认情况下无法设置单选按钮
【发布时间】:2020-02-03 08:14:29
【问题描述】:

Vue documentation 表示如果 v-model 的初始值与单选值不匹配,则会显示为未选中。我认为我做的一切都是正确的,但默认情况下仍然没有检查广播公共。

组件无线电:

<template>
  <div>
    <input
      type="radio"
      :id="identifier"
      :value="identifier"
      :name="name"
      ref="radio"
      @input="updateRadio()"
      :checked="checked"
    >
    <label :for="identifier">
      <span>{{label}}</span>
    </label>
  </div>
</template>

<script>
export default {
  props: ["value", "name", "identifier", "label", "checked"],

  methods: {
    updateRadio() {
      this.$emit("input", this.$refs.radio.value);
    }
  }
};
</script>

Vue 用法

<Radio v-model="share" identifier="public" label="Public" name="share"/>
<Radio v-model="share" identifier="private" label="Private" name="share"/>

export default {
  name: "SignUpForm",
  components: {
    Radio
  },
  data: () => ({
    share: "public"
  })
};

我查看了其他相关问题,但没有发现差异

小提琴:https://codesandbox.io/s/funny-antonelli-yoblx

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

    在您的组件单选中将检查的指令值更改为 :checked="value"

    Radio.vue

    <template>
      <div>
        <input
          type="radio"
          :id="identifier"
          :value="identifier"
          :name="name"
          ref="radio"
          @input="updateRadio()"
          :checked="value === identifier"
        >
        <label :for="identifier">
          <span>{{label}}</span>
        </label>
      </div>
    </template>
    
    <script>
    export default {
      props: ["value", "name", "identifier", "label", "checked"],
    
      methods: {
        updateRadio() {
          this.$emit("input", this.$refs.radio.value);
        }
      }
    };
    </script>
    

    【讨论】:

    • 我更新它。对不起,我认为这是因为检查指令是布尔值,现在我添加了一个条件来检查。
    • 谢谢,现在可以使用了。我最初尝试布尔类型也没有运气。
    最近更新 更多