VueJs Filters

In VueJs, you can register your filters in two different ways: Globally and Locally.

Filters are JavaScript functions, they take the value to be transformed as the first parameter, but you can also pass in as many other arguments as you will need to return the formatted version of that value.

VueJs Global Filters

Here is what a Global filter looks like:

Note: The filter definition must always be above the main Vue instance.

<script>
Vue.filter('toUSD', function(value) {
  return `$${value}`;
});
</script>
<!DOCTYPE html>
<html lang="en">
<head>
   <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
     <script>
     new Vue ({
        	el: '#app',
		data: {
		        price: 5000
		}
             })
   </script>
   <div id="app">
      <span>{{ price | toUSD }}</span>
   </div>
 </body>
</html>

Output

{{ price | toUSD }}

VueJs Local Filters

Here is what a Local filter looks like:

<!DOCTYPE html>
<html lang="en">
<head>
   <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
     <div id="app1">
       <span>{{ price | toUSD }}</span>
     </div>
     <script>
     new Vue ({
        	el: '#app',
		data: {
		     price : 1500,
		},
		 filters : {
		                 toUSD : function(value) {
			                return `$${value}`
			          }
		             }
	})
   </script>
 </body>
</html>

Output

{{ price | toUSD }}