Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Adding elements to the end of the array using filters in Vue.js

  • Last Updated : 25 Mar, 2021

In this article, we are going to learn how to add elements to the end of an array in VueJS. Vue is a progressive framework for building user interfaces. 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.

The adding of elements at the end of the array can be performed by applying a filter on the required array. We use the rest parameters of the array to add an indefinite amount of items to the array. The spread syntax is used to spread the existing list items first and then adding the new items at the end. This results in a new array that contains the old elements as well as new required elements at last.

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

We cannot call a vue filter in loops in the traditional way. We have to call the Vue filter a method of object filters.

Syntax: To call a filter in vue loops.



$options.filters.addLast(data, other_parameters)

Example: In this example we loop over the array and show them as a list of item. Similarly, when we try to list the final array list after the addition of the new items we have to call the required filter in the Vue loop as explained above.

index.html




<html>
<head>
  <script src="
  </script>
</head>
<body>
  <div id='parent'>
    <p>
      <strong>List : </strong>
      <ol>
        <li v-for='item in arr1'>
          <strong>{{item}}</strong>
        </li>
      </ol>
      <strong>Final List : </strong>
      <ol>
        <li v-for=
'item in $options.filters.addLast(arr1, ["Rice","Bread","Milk"])'>
          <strong>{{ item }}</strong>
        </li>
      </ol>
    </p>
  
  </div>
  <script src='app.js'></script>
</body>
</html>

app.js




const parent = new Vue({
  el: '#parent',
  data: {
    arr1: ['Vegetables', 'Eggs', 'Fruits', 'Coffee']
  },
  
  filters: {
    addLast: function (arr, item_arr) {
  
      // Using the spread syntax to add the
      // items to the end of the array
      const final_list = [...arr, ...item_arr]
      return final_list
    }
  }
})

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!