VUEX for VUE component

40 Views Asked by At

I have a VUE component JobComponent.vue and I use VUEX to get data from jobs.js. When I use this component in Home.vue I want to render it just for five times and in reverse mode, just the last 5 items starting with the last one. Now, it renders 7 times, because of the v-for from JobComponent.vue.

JobComponent.vue

<div v-for="job in allJobs" :key="job.id" class="card">
    <div class="position">{{ job.position }}</div>
    <div class="department">{{ job.department }}</div>
    <div class="location">
      <span class="material-symbols-outlined">location_on</span>
      {{ job.location }}
    </div>
    <span class="material-symbols-outlined right-arrow">arrow_right_alt</span>
    <span @click="deleteJob" class="material-symbols-outlined right-arrow">delete</span>
  </div>

Home.vue

  <div class="cards-container">
      <JobComponent />
  </div>

jobs.js

const state = {
    jobs: [
        {
            position: "2",
            department: "2",
            location: "2",
            id: 2
          },
          {
            position: "3",
            department: "3",
            location: "3",
            id: 3
          },
          {
            position: "4",
            department: "4",
            location: "4",
            id: 4
          },
          {
            position: "5",
            department: "5",
            location: "5",
            id: 5
          },
          {
            position: "6",
            department: "6",
            location: "6",
            id: 6
          },
          {
            position: "7",
            department: "7",
            location: "7",
            id: 7
          }
    ]
};

Before VUEX I was fetching data in every VUE file that I need, I used v-for with slice() and reverse() method.

1

There are 1 best solutions below

3
homayounKh On

You can define allJobs as vuex getters and use computed property for what you want.

computed: {
  allJobs() {
    return this.$getters.allJobs.reverse().slice(0, 5);
  }
}