Skip to content
Advertisement

Issue when trying to show only specific array id value inside of component in Vuejs?

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>

      <router-link name="twoval"></router-link>
    </div>
    <br /><br /><br />
    <User />
    <Usertwo />
  </div>
</template>

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

User.vue

<template>
  <div>
    <div v-for="(item, key) in user" :key="key">
      {{ item }}
    </div>
  </div>
</template>

<script>
import { datalist } from "./datalist";
export default {
  name: "User",
  data() {
    return {
      lists: datalist,
    };
  },
  computed: {
    user: function () {
      return this.lists.find((item) => item.id === this.$route.params.id);
    },
  },
};
</script>

Usertwo.vue

<template>
  <div>
    <div v-for="usertwo in usertwos" :key="usertwo.mid">
      {{ usertwo.doctor }}
    </div>
  </div>
</template>

<script>
import { datalisttwo } from "./datalisttwo";
export default {
  name: "User",
  data() {
    return {
      usertwos: datalisttwo,
    };
  },
};
</script>

main.js

import Vue from "vue";
import App from "./App.vue";
import VueRouter from "vue-router";
import HelloWorld from "./components/HelloWorld.vue";

Vue.use(VueRouter);

const router = new VueRouter({
  routes: [
    { path: "/", name: "User", component: HelloWorld },
    { path: "/:id", name: "UserWithID", component: HelloWorld }
  ]
});

Vue.config.productionTip = false;

new Vue({
  router,
  render: (h) => h(App)
}).$mount("#app");

Logic trying to achieve, If i click on router-link id-1 from helloworld.vue component, then in User.vue and Usertwo.vue component. I need to show only array values list which is linked with id-1 only. from two arrray value list based on id.

Similarly on whatever the id, i click on from router-view from helloworld.vue. Same id value, i need to show inside the User and Usertwo.vue component.

Now only issue wit code is, Usertwo array value not loading correctly

I tried below code for that logic, But i couldn’t make it. This is my complete code:- https://codesandbox.io/s/pensive-williamson-n9bi6?file=/src/main.js:0-434

Advertisement

Answer

Something like this: https://codesandbox.io/s/white-bird-z6orf

  1. Add props to the components
  2. Send the id from the params to the components
  3. Filter the list
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement