Search code examples
vue.jsvuetify.js

Vuetify : How to get the value of a prefix from a text field


I have a form in my page with various text fields, on one of them I put a prefix because I want the value entered to always start with the same 5 letters.

I was able to get my value from the text field to my save method but not the prefix and I can't add it manually while saving because the value will depend on what type the user choses, I will try to explain this :

  • If the user choses Type A there will be no prefix and the value will be saved as it is entered by the user.
  • If the user choses Type B there will be a prefix in the text field and the value will be saved with prefix + value entered by the user.

Here's the code I have for now : Both my text fields depending on which type the user choses :

  <v-col v-show="type === 'TypeA'">
    <v-text-field
      v-model="id"
      clearable
      required
      light
      solo
      dense
      max-length="36"
      :rules="idRule"
    >
    </v-text-field>
  </v-col>
  <v-col v-show="type === 'TypeB'">
    <v-text-field
      v-model="id"
      clearable
      required
      light
      solo
      dense
      max-length="31"
      prefix="ABCDE"
      :rules="idRule"
    ></v-text-field
  ></v-col>

And this is what I do in my save method :

await this.$axios.$post(uri, {
  id: this.id,
});

I probably can get away with adding it later depending on which type is chosen but I want the user to see the prefix, so is there a way I can get the prefix from the text field directly ?


Solution

  • If the prefix was a variable, you could just add the prefix value to the id value when saving. You also wouldn't need two different v-text-field components just to handle different prefixes since the prefix can be dynamically updated based on type. A computed property would probably be easiest.

    <v-text-field
      v-model="id"
      :prefix="prefix"
    ></v-text-field>
    
    computed: {
      prefix() {
        return this.type === 'TypeB' ? 'ABCDE' : ''
      },
    },
    
    ...
    
    save() {
      await this.$axios.$post(uri, {
        id: this.prefix + this.id,
      });
    }
    

    demo