Home > Back-end >  Connect source data in v-for loop with props value
Connect source data in v-for loop with props value

Time:10-02

I have imported multiple json files with different data.

Based on my input in my parent.vue I want to loop through different json files.

<div v-for="(item, index) in <!-- JSONFile   Rank -->" :key="index">

my script for this:

import json1 from './components/json1.json'
import json2 from './components/json2.json'
import json3 from './components/json3.json'

export default {
data() {
  return {
    JSONFile1: json1,
    JSONFile2: json2,
    JSONFile3: json3,
  }
}

props: [
  "Rank" //1, 2 or 3, based on input in parent.vue 
  ]
}

Just for your understanding - manually it looks like this:

<div v-for="(item, index) in JSONFile1" :key="index">

OR

<div v-for="(item, index) in JSONFile2" :key="index">

First code-line above should represent if props-value is 1, second code-line if it is 2.

CodePudding user response:

You can create a JSONFiles array instead of 3 different variables:

import json1 from './components/json1.json'
import json2 from './components/json2.json'
import json3 from './components/json3.json'

export default {
data() {
  return {
    JSONFiles: [json1, json2, json3]
  }
}

  props: [
    "Rank" //1, 2 or 3, based on input in parent.vue 
  ]
}

Then you can access them by JSONFiles[Rank]:

<div v-for="(item, index) in JSONFiles[Rank]" :key="index">
  • Related