VUE 3对同一组件使用不同的v-for

tvz2xvvm  于 2022-12-14  发布在  Vue.js
关注(0)|答案(1)|浏览(154)

我有一个JobComponent.vue组件,我在其中从VUEX Store获取数据。此组件用于两个单独的页面,第一个页面Home.vue和第二个页面AllJobs.vue。在AllJobs.vue中,我使用了JobComponent.vue,一切正常,它呈现了所有作业,但是,问题来了...
Home.vue中,我只想渲染最后5个作业,所以在store中我创建了一个 getter,它只对最后5个作业进行切片。
如何在同一组件上使用来自 getterslatestJobs
Home.vue页面中导入组件时,无法在组件上使用另一个 v-for direct...
here you can see my project structure and files

首页.版本

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

作业组件.vue

<template>
  <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(job.id)" class="material-symbols-outlined right-arrow">delete</span>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';

export default {
  methods: {
    ...mapActions(['fetchJobs', 'deleteJob']),
  },
  computed: mapGetters(['allJobs']),
  created() {
    this.fetchJobs();
  }
}
</script>

存储.js(vuex)

const getters = {
    allJobs: (state) => state.jobs,
    
    latestJobs: (state) => {
        const response = state.jobs.slice(0, 5);

        return response;
    }
};
snvhrwxg

snvhrwxg1#

你的组件应该尽可能独立于商店。它的作用是展示所提供的东西,以便你可以使用 prop 来重用它:

作业组件.vue

<template>
  <div class="card">
    <div class="position">{{ position }}</div>
    <div class="department">{{ department }}</div>
    <div class="location">
      <span class="material-symbols-outlined">location_on</span>
        {{ location }}
    </div>
    <span class="material-symbols-outlined right-arrow">arrow_right_alt</span>
    <span @click="$emit('deleteJob', id)" class="material-symbols-outlined right-arrow">delete</span>
  </div>
</template>

<script>
export default {
  props: {
    id: string,
    position: string,
    department: string,
    location: string
  }
}
</script>

在此组件中,您仅显示提供的数据,并让父组件负责选择要显示的组件数量。
首页

<template>
  <div class="cards-container">
    <JobComponent v-for="job in jobs" :key="job.id" :id="job.id" :position="job.position" :department="job.department" :location="job.location" @delete-job="deleteJob" />
  </div>
</template>

<script>
export default {
  created() {
    this.$store.dispatch('fetchJobs')
  },
  computed: {
    jobs() {
      return this.$store.getters['latestJobs'] // Or allJobs, just make sure your getter returns an array even if no jobs are loaded yet.
    }
  },
  methods: {
    deleteJob() {
      // Your logic for job delete
    }
  }
}
</script>

相关问题