Saturday, December 28, 2024
Google search engine
HomeLanguagesJavascriptPluralize data according to its count using Vue Filters

Pluralize data according to its count using Vue Filters

Vue is a progressive framework for building user interfaces. The core library is focused on the view layer only and is easy to pick up and integrate with other libraries. Vue is also perfectly capable of powering sophisticated Single-Page Applications in combination with modern tooling and supporting libraries.

Filters are a functionality provided by Vue components that let you apply formatting and transformations to any part of your template dynamic data. The filter property of the component is an object. 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. 

For pluralizing data according to its count, we have to write the filter logic to show data in singular and plural forms. We simply check if the given count is equal to 1 and depending on the result decide to display the singular or plural forms.

Example:

index.html




<html>
<head>
  <script src=
  </script>
</head>
<body>
  <h1 style="color: green;">neveropen</h1>
  <div id='parent'>
    <p><strong>No. of item: </strong
      {{ c1 | pluralize('Book','Books') }}
    </p>
  
    <p><strong>No. of item: </strong
      {{ c2 | pluralize('Chair','Chairs') }}
    </p>
  
    <p><strong>No. of item: </strong>
      {{ c3 | pluralize('Potato Fry','Potato Fries') }}
    </p>
  
    <p><strong>No. of item: </strong>
      {{ c4 | pluralize('Ice Cream','Ice Creams') }}
    </p>
  
    <p><strong>No. of item: </strong>
      {{ c5 | pluralize('Mobile','Mobiles') }}
    </p>
  
  </div>
  <script src='app.js'></script>
</body>
</html>


app.js




const parent = new Vue({
  el: "#parent",
  data: {
    c1: 1,
    c2: 5,
    c3: 100,
    c4: 10,
    c5: -9,
  },
  
  filters: {
    pluralize: function (count, sing, plur) {
  
      // Decide to pluralize based
      // on the count
      if (count == 1) {
        return count + ` ${sing}`;
      } else if (count > 1) {
        return count + ` ${plur}`;
      } else {
        return "Please pass valid count of data";
      }
    },
  },
});


Output:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments