Adam Allen
Adam Allen

Reputation: 208

Class not being added in VUE

I have a input filed and when it is typed in i have a method which checks the length of the inputted string, this works fine, however i now want to add a class depending on the length of the string.

This is my template element:

<input v-model=“categoryTitle” v-bind:class="{ ‘passed’: isPassed }" @keyup=“addName” type=“text” name=“desc” id=“desc” value="" data-original="" placeholder="">

and this is my data and method:

data:{
categoryTitle:’’,
isPassed:false,
},
methods: {

        addName(){

            if(this.categoryTitle.length < 100 && this.categoryTitle.length > 0){
                this.isPassed = true;
            }

        },

    }

But nothing is happening, what am i doing wrong? i am still quite new to VUE so im sure it is a rookie error.

Upvotes: 0

Views: 57

Answers (1)

thanksd
thanksd

Reputation: 55664

Just make isPassed a computed property:

computed: {
  isPassed() {
    let length = this.categoryTitle.length;
    return length < 100 && length > 0;
  }
}

That way you don't need to update the property by listening to an event on the input. The computed property will update automatically when the value of the dependant categoryTitle property changes.

Here's a working example:

new Vue({
  el: '#app',
  data() {
    return { categoryTitle: '' }
  },
  computed: {
    isPassed() {
      let length = this.categoryTitle.length;
      return length < 100 && length > 0;
    }
  }
})
  
.passed { color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.js"></script>
<div id="app">
  <input v-model="categoryTitle" v-bind:class="{ passed: isPassed }">
</div>

Upvotes: 2

Related Questions