[Vuejs]-Vuex get for loop id to axios

0👍

It’s recommended doing the mapping on the basis of id in a getter / computed
itself ie. before rendering the data in the <template>

// vuex
getters: {
 getPosts: state => {
  return state.posts.map(post => {
   let lesson = state.lesson1.find(lesson => lesson.id == post.id)
   return { ...lesson, ...post }
  })
 }
}

// template
<ul v-for="post in posts" :key="post.id">
 <li>
  <h1>{{ post.name}}</h1>
  <slide><img :src="post.image_url"></slide>
 </li>
</ul>

// script
import { mapGetters } from 'vuex'
export default {
 computed: {
  ...mapGetters(['getPosts']) // After mapping the getter, you can use `getPosts` in your template
 }
}

Alternative: you can use v-if directive to avoid rendering the element if id does not match.

// template
<ul v-for="post in posts" :key="post.id">
 <li>
  <h1>{{ post.name}} </h1>
  <template v-for="(lesson, index) in lesson1" :key="index" class="parent">
   <slide v-if="post.id == lesson.id" class="child"> <-- here
    <img :src="lesson.image_url">
   </slide>
  </template>
 </li>
</ul>

Note: Vue won’t let you put both v-for & v-if on the same element so have wrapped <slide> with a <div>

Leave a comment