Get filtered items in Vue.js/Vuex/ES6 using getters

in Code Write a comment

In this tutorial, you’ll learn how to get filtered items from an array using store getters.

Array.filter() example

Array.filter() method is used to create a new array that passes the certain condition created by the provided function. E.g. we can

var headsets = ['Hololens', 'Google Glass', 'Varjo'];

console.log(headsets.filter((headset) => headset.startsWith("G")));
// expected output: ["Google Glass"]

Vue.js example using Vuex store getter

Suppose we have a list of products in a Vuex state. Each product has an “is_active” field. Our task is to get a list of all active products from the Vuex state.

getActiveProducts (state) {
  if (state.products) {
    return state.products.filter((product) => {
      return product.is_active
    })
  }
}

Hi, I'm Renat 👋

 


In the example above, we are using getActiveProducts() getter to filter all the active products from the list and return it as an array.

You can then call this getter inside your project to get a list of active products from a Vuex state.

this.$store.getters.getActiveProducts

The mapGetters() helper

Or get a list of products using the mapGetters() helper, by mixing the getters into computed with object spread operator

computed: {
  ...mapGetters({
    activeProducts: 'getActiveProducts'
  })
}

If you find this post useful, please let me know in the comments below. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/vuex-vuejs-getters

PS: Make sure you check other Vue.js tutorials, e.g. vue.js scroll to top on route change, get filtered items in Vue.js/Vuex/ES6 using getters, binding HTML classes in Vue.js.

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment