Display user information from another component using Vue's dynamic routing feature

In my UserList.vue component, I have a list of users that I want to display on individual user profiles in the SingleUser.vue component. What is the easiest way to achieve this?

The user details are stored in the UserList.vue component. When a specific user link is clicked, I want to navigate to their profile.

Router paths: /user/1, /user/2, /user/3, etc.

UserList.vue:

<template>
  <v-list two-line>
    <template v-for="(user) in users">
      <v-list-item
          :key="user.username"
      >
        <router-link
            :to="`user/${user.id}`"
        >
          <v-list-item-avatar>
            <v-img :src="user.avatar"></v-img>
          </v-list-item-avatar>
        </router-link>

        <v-list-item-content>
          <router-link
              :to="`user/${user.id}`"
          >
          <span class="name">
            {{ user.name }}
          </span>
            <span class="username">
            {{ user.usernaname }}
          </span>
          </router-link>
        </v-list-item-content>
      </v-list-item>
    </template>
  </v-list>
</template>

<script>
export default {
  data: () => ({
    users: [
      {
        id: 1,
        username: 'johndoe',
        name: 'John Doe',
        avatar: require('@/assets/images/john-doe.png'),
      },
      {
        id: 2,
        username: 'bobdoe',
        name: 'Bob Doe',
        avatar: require('@/assets/images/bob-doe.png'),
      },
      {
        id: 3,
        username: 'annedoe',
        name: 'Anne Doe',
        avatar: require('@/assets/images/anne-doe.png'),
      },
    ],

  }),
}
</script>

SingleUser.vue (Single user profile):

<template>
  <h1>{{ user.name }}</h1>
  <h2>{{ user.username }}</h2>
  <v-img :src="user.avatar"></v-img>
</template>

<script>

</script>

router.js:

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
  {
  path: '/',
  name: 'Home',
  component: Home
  },
  {
  path: '/users',
  name: 'Users',
  component: () => import('../views/UserList.vue')
  },

  {
  path: '/user/:id',
  name: 'User',
  component: () => import('../views/SingleUser.vue')
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

Answer №1

Within my Vue 2 CLI sandbox app, I devised a sample application to demonstrate functionality. In this rendition, I opted for Vuex to manage user data instead of making API calls. Additionally, I utilized a basic <ul> structure instead of Vuetify components and omitted image elements. Nevertheless, the routing mechanism remains intact for seamless integration into your project.

UserList.vue

<template>
  <div class="user-list">
    <h3>User List</h3>
    <div class="row">
      <div class="col-md-6">
        <ul>
          <li v-for="user in users" :key="user.id">
            <router-link :to="{ name: 'User', params: { id: user.id }}">{{ user.name }}</router-link>
          </li>
        </ul>
          </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'UserList',
    data() {
      return {
        users: [
          {
            id: 1,
            username: 'johndoe',
            name: 'John Doe',
          },
          {
            id: 2,
            username: 'bobdoe',
            name: 'Bob Doe',
          },
          {
            id: 3,
            username: 'annedoe',
            name: 'Anne Doe',
          },
        ]
      }
    },
    created() {
      this.$store.commit('initUsers', this.users);
    }
  }
</script>

SingleUser.vue

<template>
  <div class="single-user">
    <h3>Single User</h3>
    <div class="row">
      <div class="col-md-6">
        <h4>{{ user.name }}</h4>
        <h4>{{ user.username }}</h4>
        <router-link :to="{ name: 'Users' }">Back</router-link>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'SingleUser',
    props: {
      id: {
        type: Number,
        required: true
      }
    },
    computed: {
      user() {
        return this.$store.getters.getUser(this.id);
      }
    }
  }
</script>

/router/index.js

import Vue from 'vue'
import VueRouter from 'vue-router'
import UserList from '@/components/stackoverflow/router-link/UserList'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/users'
  },
  {
    path: '/users',
    name: 'Users',
    component: UserList
  },
  {
    path: '/user/:id',
    name: 'User',
    component: () => import('@/components/stackoverflow/router-link/SingleUser'),
    props: true
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

/store/index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    users: []
  },
  getters: {
    getUser: (state) => (id) => {
      return state.users.find( user => user.id === id);
    }
  },
  mutations: {
    initUsers(state, newUsers) {
      state.users = newUsers;
    }
  }
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is the button missing from the codepen?

I attempted to recreate the code from this Codepen link: https://codepen.io/jakaric/pen/mjJQvg However, unlike what you see here (in the run result), the liquid "Pretty little button" is not showing up in my local files. On Codepen, there is no library me ...

Observing modifications in the database is possible after executing the setInterval function

I am using a JavaScript function that runs every 4 seconds with setInterval. Once this function is executed for the first time, it calls an ajax request and changes a column value in the database. I want to know how I can check if this value has been succe ...

Despite my attempts to force a repaint, the progress bar remained static during intensive tasks

My JavaScript method works fine in Chrome, taking about 2000 ms to iterate over ~200 inputs, insert values, and trigger onchange events. However, it's a different story in IE where it takes about 10000 ms. To show the progress of this process, I deci ...

How come the light position is not updating?

I am currently using the three.js library to create an animated cylinder: let renderer, camera, scene, light, cylinder; initialize(); animate(); function initialize() { renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true }); renderer ...

Using Vue.js to showcase real-time Pusher data in Laravel 5.4

I am currently working on developing a real-time chat application using vue.js, Pusher, and Laravel. I have successfully managed to receive information from Pusher, as I can view the JSON data in the console with the correct details. However, I am facing a ...

The offsetTop property of Angular's nativeElement always returns a value of 0

I am currently working on a menu that will automatically select the current section upon scrolling. However, I am running into an issue where I am consistently getting a value of 0 for the offsetTop of the elements. The parentElement returns a value for of ...

Include and run a series of scripts in the package.json file

Exploring Node.js for the first time, I find myself in need of adding a series of scripts to package.json and running them one by one. Is this achievable with Node.js? "scripts": { "sample": "run --spec '*spec.js'&quo ...

Passing JSON data with special characters like the @ symbol to props in React can be achieved

Using axios in React, I am fetching JSON data from a database. I have successfully retrieved the JSON data and stored it in state to pass as props to child components within my application. However, the issue arises when some of the objects in the JSON s ...

Error: The function used in Object(...) is not defined properly in the useAutocomplete file at line 241

I am currently working on a ReactJS application that utilizes Material UI components without the use of Redux. Everything is functioning properly in my application, except when I attempt to integrate the Material UI autocomplete feature, it encounters iss ...

Progression from Angular2-rc1 to Angular2-rc2 encounters TypeScript error: anticipating ',' (TS1005)

Encountering an issue with upgrading Angular2 from RC1 to RC2, following exception is being thrown: Here's my main.ts file, I haven't made any changes to it during the upgrade process. Line 13 is where the bootstrap method is called. import {pr ...

Accessing a span element using an eval function

I have a function that accesses an input element and updates its value using the following line of code: eval('document.forms[0].telephone').value = $telephone[$i]; Now, I need to transfer this value to a span, but I'm having trouble refer ...

Access a folder in JavaScript using Flask

I need to specify a directory in a script. $images_dir = '{{url_for('.../pictures')}}'; In my flask application directory structure, it looks like this: Root -wep.py -templates -gallery.html -static -pictures The images are stored ...

Steps for setting up node-openalpr on a Windows 10 system

While attempting to install npm i node-openalpr, an error is occurring: When using request for node-pre-gyp https download, I encounter a node-pre-gyp warning and error message. The package.json for node-openalpr is not node-pre-gyp ready, as certain pr ...

Does the execution of node.js event handlers occur when the calling stack is clear?

My belief that code related to node.js events is asynchronous was challenged when I came across the following example: var EventEmitter = require('events').EventEmitter; var emitter = new EventEmitter(); emitter.on('foo', function () ...

Struggling to integrate Material UI (MUI) into my React application

I have followed all the necessary steps to install materialUI, emotion/react, and emotion/styled in my react app. However, I am encountering an issue where MUI does not seem to work properly. There are no errors displayed on the console or webpage, but not ...

Vuetify's DarkMode color scheme appears distorted upon refreshing the page

After successfully implementing dark mode toggling in my Vuetify App (yay!), I encountered an issue where the style colors do not update to dark mode after a full page refresh. The primary color from light mode persists. Interestingly, when switching back ...

Angular app - static List mysteriously clears out upon refresh

My goal is to create a login page using Angular. I have an Angular component with HTML, CSS, and TypeScript files that manage this functionality. The HTML file contains two fields (Username and Password) and two buttons (Login and Register). When a user en ...

Retrieve specific information from checkboxes within a form

I'm working on a form that includes multiple checkboxes populated with data from a JSON file using ng-repeat. After submitting the form, I need to retrieve the data from the checked checkboxes. How can I accomplish this in my controller after the form ...

Tips on utilizing jQuery or JavaScript to efficiently filter out outcomes exceeding a specified range

<input type="range" name="rangeInput" min="100000" max="750000" onchange="updateTextInput(this.value);"> Displayed above is the slider code that provides a value output below. <div id="sliderValue"> <p>Max Value £</p> <input t ...

The Bootstrap modal stubbornly refuses to close even after resetting the HTML body

I am having an issue with my bootstrap modal where the closeModal button is not functioning properly after the printModal button has been clicked. The modal does not close as expected. Step 1: Click on the printModal button after the modal pops up (this w ...