Filtering with Vue.js

Filtering with Vue

Introduction

A Vue filter is essentially a function that takes a value, processes it, and then returns the processed value. Filters are not substitutes for methods, computed properties or watch properties, because filters do not transform data, but merely transform the output that the user sees.

Filters can overlap one another, and like all functions, they can accept arguments. When a filter is used, its context is set to the instance that invokes it, hence the keyword “this” points to it.

List of sites that offer pre-made filters:

Registering filters

Filters can be registered globally and locally.

Local registration

filters: {
  filterName(value) {
    return // thing to transform
  }
}

Global Registration

Vue.filter('filterName', function(value) {
  return // thing to transform
});

REMARK:
The code that defines the filter globally must be written before the code that defines the instance

Example

In this example, we define a filter that transforms the output of text so that the beginning of each new word begins with a capital letter.

Vue.filter('camel',function(str){
    return str.toLowerCase().replace(/^\w|\s\w/g, function (letter) {
        return letter.toUpperCase();
    })
})
new Vue({
  el: '#app',
  template: '<App/>',
  components: { App }
})

Using filters

Filters can be implemented in two ways: mustache interpolations and v-bind expressions

a) Integration with interpolation

Filters are integrated as an interpolation term by overriding the expression they need to transform with the special “|” (pipe) character:

{{message | filtername}}

Filters can be refilled:

{{ message | filterA | filterB }}

And since filters are actually functions, then they can receive arguments:

	
{{ message | filterA('arg1', arg2) }}

Example

HTML

<div id = "app">
   <h2> Discount Calculator </h2>
   <p> <strong> Standard Price: {{customer1total}} </strong> </p>
   <p> Discount price 15%: {{customer1total | discount15}} </p>
   <p> Discount price 20%: {{customer1total | discount20}} </p>
   <p> Discount Price 25%: {{customer1total | discount25}} </p>
</div>

SCSS

#app {
  text-align: center;
  max-width: 25rem;
  margin: 1rem auto;
  display: table;
  padding: 1rem 2rem;
  border: 1px solid black;
}

h2 {
  border-bottom: 1px solid #ccc;
}

Babel

new Vue ({
   el: '#app',
   data () {
     return {
       customer1total: 35.43
     }
   },
   filters: {
     discount15 (value) {
       return (value * .85) .toFixed (2)
     },
     discount20 (value) {
       return (value * 0.8) .toFixed (2)
     },
     discount25 (value) {
       return (value * .75) .toFixed (2)
     }
   }
});

b) Integration with v-bind

<div v-bind: id = "rawId | FilterName"> </div>

Likes:
15 0
Views:
1759
Article Categories:
PROGRAMMINGTECHNOLOGY

Leave a Reply

Your email address will not be published. Required fields are marked *