How to change append-icon of vuetify v-text-field based on its valid state

Viewed 37

I'm fairly new to vuetify and was wondering if the append-icon prop of v-text-field can be dynamic based on the valid state of the field. I need 2 options:

Option 1: If there is an error it can be the red alert icon. If its valid it can change to a green checkmark.

Option 2: Only show the error icon if there is an error else hide it.

<v-text-field
        v-model="firstname"
        :rules="nameRules"
        class="text-field"
        append-icon="mdi-alert-circle-outline"
        placeholder="Enter first name"
        hide-details="auto"
        outlined
        required
      >
      </v-text-field>
1 Answers

Check this codesanbox I made: https://codesandbox.io/s/stack-73601258-dynamic-prepend-icon-uq729h?file=/src/components/Example.vue

Vuetify components have a thing called slots that you can modify to extend it's functionality. You can find the available slots for each vuetify component at their API documentation page: https://vuetifyjs.com/en/api/v-text-field/#slots

In this example I modified the icon append slot

<v-form v-model="validForm" ref="myForm" lazy-validation>
   <v-card class="pa-5">
      <v-text-field v-model="text" :rules="textRules" label="My text field">
         <template v-slot:append>
            <v-icon v-if="validForm && text.length > 0" color="green">
               mdi-check
            </v-icon>
            <v-icon v-if="!validForm" color="red">
               mdi-alert-circle-outline
            </v-icon>
         </template>
      </v-text-field>
      <v-btn :disabled="!validForm" color="primary" @click="submitForm">
         Submit
      </v-btn>
   </v-card>
</v-form>

Preview

Related