How to concat arrays in vuex getters?

by filiberto , in category: Javascript , a year ago

How to concat arrays in vuex getters?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by gilbert , a year ago

@filiberto 

To concatenate arrays in Vuex getters, you can use the spread operator along with the concat method. Here's an example:

  1. In your Vuex store module, define a getter that returns an array:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// storeModule.js
const state = {
  array1: [1, 2, 3],
  array2: [4, 5, 6]
};

const getters = {
  concatenatedArray: state => {
    return [...state.array1, ...state.array2];
  }
};

export default {
  state,
  getters
};


  1. Import the store module and use the getter in your component:
1
2
3
4
5
6
7
8
9
// YourComponent.vue
import { mapGetters } from "vuex";

export default {
  computed: {
    ...mapGetters("storeModule", ["concatenatedArray"])
  },
  //...
};


  1. Use the getter value in your component template:
1
2
3
4
5
6
7
8
<!-- YourComponent.vue -->
<template>
  <div>
    <ul>
      <li v-for="item in concatenatedArray" :key="item">{{ item }}</li>
    </ul>
  </div>
</template>


In the above example, the concatenatedArray getter concatenates array1 and array2. The spread operator ... is used to separate the elements of both arrays while concatenating them. The resulting combined array is then returned by the getter and can be accessed in the component through mapGetters.