18

I trying to make some data to lowercase (alway lowercase)

I making and search input like :

<template id="search">
    <div>
        <input type="text" v-model="search">
        <li v-show="'hello'.includes(search) && search !== ''">Hello</li>
    </div>
</template>

Vuejs : (component)

Vue.component('search', {
    template : '#search',
    data: function(){return{
        search : '',
    }}
});

I tried watch, But I dont want input showing lowercase when typing

watch: {
    'search' : function(v) {
        this.search = v.toLowerCase().trim();
    }
}

Demo : https://jsfiddle.net/rgr2vnjp/


And I dont want to add .toLowerCase() on search list v-show like :

<li v-show="'hello'.includes(search.toLowerCase()) && search !== ''">Hello</li>

Any trick?, I searched and many tell just use filter but not exits on Vuejs 2

Playground : https://jsfiddle.net/zufo5mhq/ (Try to type H)

PS: Good / better code I would like to know also, Thanks

l2aelba
  • 21,591
  • 22
  • 102
  • 138

4 Answers4

26

In Vue.js 2.0, computed properties can be used to replace filters:

computed: {
  searchInLowerCase() {
    return this.search.toLowerCase().trim();
  }
}

And now you can simply use searchInLowerCase in your template:

<li v-show="'hello'.includes(searchInLowerCase) && search !== ''">Hello</li>
CodinCat
  • 15,530
  • 5
  • 49
  • 60
16

You could even do this

{{tag.title.toLowerCase().trim()}}
Mir Adnan
  • 844
  • 11
  • 24
1

Ideally, you should put all the logic in a computed, so you clearly separate the logic from the view/template:

computed: {
  showHello() {
    const trimmedSearch = this.search.toLowerCase().trim()
    return 'hello'.includes(trimmedSearch) && this.search !== ''
  }
}

Then in your template:

<li v-show="showHello">Hello</li>
Lucas
  • 1,833
  • 1
  • 18
  • 19
0

For me the best way to integrate lowercase is to use vue filters: https://v2.vuejs.org/v2/guide/filters.html

<template>
  <div>
    {{ name | lowercase}}
  </div>
</template>

<script>
  export default {
    data: () => ({
      name: 'I AM ROOT'
    })
    filters: {
      lowercase: function (value) {
        if (!value) return ''
        return (value.toString().toLowerCase())
      }
    }

  }
</script>