Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuejs 2 : How to make data lowercase

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

like image 620
l2aelba Avatar asked Apr 26 '17 07:04

l2aelba


People also ask

How to convert string in lowercase in VueJS?

A single filter is a function that accepts a value and returns another value. The returned value is the one that's actually printed in the Vue. js template. To lowercase string using filters, we have to write logic to convert a regular string into all lower case and apply the filter on a required string.

Are Vue props case sensitive?

Prop Casing (camelCase vs kebab-case)HTML attribute names are case-insensitive, so browsers will interpret upper-case characters as lower-case. This means that when they're used directly in HTML, camelCased prop names have to be changed to their kebab-case equivalent.

How do you capitalize first letter in Vue?

charAt(0). toUpperCase() + value.


3 Answers

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>
like image 133
CodinCat Avatar answered Oct 23 '22 21:10

CodinCat


You could even do this

{{tag.title.toLowerCase().trim()}}
like image 25
Mir Adnan Avatar answered Oct 23 '22 21:10

Mir Adnan


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>
like image 1
Lucas Avatar answered Oct 23 '22 22:10

Lucas