[Vuejs]-Getting textbox to turn red on change

0👍

Try watching product.name and setting this.dirty = true; there. The first time you edit the input after mounting it will fire and accomplish the same as your onChange method. Additionally, you can save some steps by conditionally applying a CSS class instead of computing it.

<template>
  <input type="text" class="form-control" :class="{ 'dirty': dirty }" v-model="product.name">
</template>

<style>
  .dirty { color: red; }
</style>

<script>
  export default {
    props: ['product'],
    data() {
      return {
        dirty: false
      }
    },
    watch: {
      'product.name': function() {
        this.dirty = true;
      }
    },
  }
</script>

0👍

This is also alternative way to style your input.

 <template>
      <input type="text" class="form-control" :class="{ 'dirty': product.name.length > 0}" v-model="product.name">
    </template>
    
    
    <style>
      .dirty { color: red; }
    </style>

Leave a comment