CodeOrc.com - Learn by example
X
Make an RPG
Vue Implementations

Example of how to use Vue Filters

Filters can be used in 2 places: Mustache interpolation or v-bind expressions

Mustache Interpolations

In the following example, lemonade pricing is cut in half by a filter.

<div id="demo"> Lemonade: {{ price | cut-price }} </div>
new Vue({ el: "#demo", filters: { "cut-price": function( value ) { return value / 2; } }, data: { price: 50 } });
DO IT

V-bind expressions

Here it is using v-bind expressions

<div id="demo"> <div v-bind:final= "price | cut-price"> Lemonade </div> </div>
new Vue({ el: "#demo", filters: { "cut-price": function( value ) { return value / 2; } }, data: { price: 50 } });
DO IT

After you run this, if you open up your debugger, you'll notice that the final attribute is 25.

Global Filters

In the previous examples, the filters only apply to the vue instance in which they appear. But, we could have defined the filter globally. This is an example of a global filter that will apply to every Vue instance:

Vue.filter("cut-price", function() { return value / 2; });
DO IT

Filter Arguments

Filters are functions, so they can take arguments, such as in this example:

<div id="demo"> Lemonade {{ price | cut-price(0.75) }} </div>
Vue.filter("cut-price", function( value, arg1 ) { var ratio = 1 - arg1; return value * ratio; });
DO IT

Chaining Filters

You can chain together multiple filters, for example:

<div id="demo"> Lemonade {{ price | cut-price(0.75) | round }} </div>
Vue.filter("round", function( value ) { return Math.round(value); }); Vue.filter("cut-price", function( value, arg1 ) { var ratio = 1 - arg1; return value * ratio; });
DO IT

You can chain together as many functions as you like. They don't have to return numbers. It can be strings, objects, arrays, etc.

In the next lesson, we will learn about Example of how to use State Transitions

Get the Latest Tutorial Updates
<< >>
X