Home > front end >  How to dynamically get the array value list based on the 'id' in Vuejs?
How to dynamically get the array value list based on the 'id' in Vuejs?

Time:01-18

**User.vue**

<template>
  <div>
    <div v-for="list in lists" :key="list.id">{{ list.val }} {{ list.kk }}</div>
  </div>
</template>

<script>
import { datalist } from "./datalist";
export default {
  name: "User",
  data() {
    return {
      lists: datalist,
    };
  },
};
</script>
**datalist.js**

export const datalist = [
  { id: 1, val: "11", kk: "potter" },
  { id: 2, val: "22", kk: "james" },
  { id: 3, val: "55", kk: "limda" },
  { id: 4, val: "77", kk: "stepen" }
];
**HelloWorld.vue**

<template>
  <div>
    <b>Vuejs dynamic routing</b>
    <div v-for="item in items" :key="item.id">
      <b>{{ item.id }}.</b> &nbsp;&nbsp;&nbsp;
      <router-link :to="{ name: 'UserWithID', params: { id: item.id } }">
        {{ item.kk }}
      </router-link>
    </div>
    <br /><br /><br />

    <b> {{ $route.params.id }}</b>
    <User />
  </div>
</template>

<script>
import User from "./User.vue";
import { datalist } from "./datalist";
export default {
  name: "HelloWorld",
  components: {
    User,
  },
  data() {
    return {
      items: datalist,
    };
  },
};
</script>

I am working on dynamic routing, Where onclick of each array value, I am getting the "id" dynamically.(like 1,2,3,4,5......)

Now I want to display the array values. specific to the id only. like...

if i click on id:1 then i need to get only the specific array values which is linked with the id:1 only. Similarry for 2,3,4....

At present problem is, If click on "array id:2" or any id valuess.. then i am getting the whole array values list.

1

11 potter 22 james 55 limda 77 stepen

Complete working code:- https://codesandbox.io/s/proud-fast-sokui?file=/src/components/HelloWorld.vue

CodePudding user response:

You can find needed user info by $route.params.id in User.vue. Example User.vue:

<div v-for="(item, key) in user" :key="key">
  {{ item }}
</div>
...
computed: {
  user: function () {
    return this.lists.find((item) => item.id === this.$route.params.id);
  },
}

Demo codesandbox

  •  Tags:  
  • Related