Learn html, css, javascript online and how to make a webpage design

How to use filter in VueJS to format data before show ?

Sunday 3rd of January 2021 09:39:28 PMVueJSFilterFilter size

When applying VueJS to your application there will be times when we need to define intermediate methods to reformat the data before it is visible to the end user. Examples are functions for date formats, currency formats, ... and many more formats.

To support the format of data before display, VueJS supports us an intermediate method to define the data display functions that is Filter.

Example Vue Filter to format the size of a file to display

<!DOCTYPE html>
<html>
<head>
    <title>How to use filter in VueJS to format data before show ? - HtmlcssDownload.com</title>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
    
<div id="app">
    <ul>
       <li v-for="(item, index) in sizeList">{{ index+1 }}. Size {{ item | formatSize }}</li>
    </ul>
</div>
   
<script type="text/javascript">

    Vue.filter('formatSize', function (size) {
       if (size > 1024 * 1024 * 1024 * 1024) {
           return (size / 1024 / 1024 / 1024 / 1024).toFixed(2) + ' TB'
       } else if (size > 1024 * 1024 * 1024) {
           return (size / 1024 / 1024 / 1024).toFixed(2) + ' GB'
       } else if (size > 1024 * 1024) {
           return (size / 1024 / 1024).toFixed(2) + ' MB'
       } else if (size > 1024) {
           return (size / 1024).toFixed(2) + ' KB'
       }
       return size.toString() + ' B'
    })

    var app = new Vue({
      el: '#app',
      data: {
         sizeList: [1412,54366,76352,9857643]
      },
      methods:{
        
      }
    })
    
</script>
    
</body>
</html>

 

 

We are Recommending you: