简体   繁体   中英

VueJS Input field value not binding

I have a problem with my generic input fields. In other words I've made a generic input field which should cover regular input fields, checkboxes and radiobuttons. But when I try to pass a string value as a value of the radio input field, the prop is empty.

 <TextInput v-model="name" description="Name & LastName" name="Name & Surname" rules="required" /> <TextInput v-model="age" type="number" description="Age" name="Age" rules="required|digits:2" /> <div id="gender-fields"> <legend>Please specify your gender:</legend> <TextInput v-model="gender" type="radio" description="Male" name="Gender" rules="required" /> <TextInput v-model="gender" type="radio" description="Female" name="Gender" rules="required" /> <TextInput v-model="gender" type="radio" description="Unspecified" name="Gender" rules="required" /> </div>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

This is how I'm declaring my input fields in my form. Here's the definiton of the Input Field.

 <template> <ValidationProvider tag="div" :rules="rules" :name="name" :vid="vid" v-slot="{ errors }" :mode="mode" > <label> {{ description }} <input :type="type" v-model="currentValue" :value="value" /> </label> <span>{{ errors[0] }}</span> </ValidationProvider> </template> <script> import { ValidationProvider } from "vee-validate"; export default { name: "TextInput", components: { ValidationProvider }, props: { description: { type: String, default: "" }, value: { required: true }, rules: { type: [String, Object], default: "" }, name: { type: String, default: "" }, vid: { type: String, default: undefined }, type: { type: String, default: "text" }, mode: { type: String, default: "aggressive" } }, data: () => ({ currentValue: "" }), watch: { currentValue(val) { // allows us to use v-model on our input. this.$emit("input", val); } } }; </script> <style></style>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
THe only input fields I have a problem with are those radio buttons. Is there something I'm missing?

The easiest way to fix this is to skip putting :value="value" on the input and change your watch like this:

  watch: {
    //watch for value to change and assign it to our currentValue
    value: {
      handler(val) {
        this.currentValue = val;
      },
      //this makes it run the handler function on mount in addition to whenever the value changes
      immediate:true
    },
    currentValue(val) {
      // allows us to use v-model on our input.
      this.$emit("input", val);
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM