Guide to clicking on a user and displaying their details in a different component or view using Vue.js router

Currently working on a Vuejs project that requires the following tasks:

  • Utilize an API to fetch and display a list of users (only user names) on the home page.

  • Create a custom search filter to find users based on their names.

  • Implement functionality where clicking on a user's name redirects to another component, displaying that specific user's details.

The first two tasks have been successfully completed. However, I am stuck on the third task. Despite referring to vue-router documentation, I am unable to resolve it.

I used axios in conjunction with jsonplaceholder to fetch the list of users.

User List Component:

<template>
    <div>
        <b-input id="inline-form-input-name" class="my-3 col-10 col-sm-10 col-md-4 col-lg-4" type="text" v-model="searchUsers" placeholder="Search Users..."
            ></b-input>
        <h2>Our users:</h2>
        <div v-for="user in filteredUsers" :key="user.id">
            <p v-b-tooltip.hover.right='"Click on user to know more"' class="users pr-2"><span>{{ user.id }}</span> - {{ user.name }}</p>
        </div>
    </div>
</template>

<script>

import axios from 'axios'

export default {
    name: 'UsersList',
    data() {
        return {
            users: [],
            searchUsers: ''
        }
    },
    computed: {
        filteredUsers() {
            return this.users.filter(user => {
                return user.name.match(this.searchUsers)
            })
        }
    },
    created(){
        axios.get('https://jsonplaceholder.typicode.com/users').then(response => {
            console.log(response.data)
            this.users = response.data
        }).catch(err => {
            console.log(err)
        })
    },
}
</script>

<style scoped lang="scss">

.users {
    cursor: pointer;
    display: inline-block;
}
</style>

The User list component is named UserList.vue

The user detail output will be displayed in the UsersDetails.vue component

<template>
    <div class="user-details-wrapper">
        <h1>I am the user details component</h1>
    </div>
</template>


<script>
export default {
    name: 'UserDetails',
    data(){
        return {

        }
    },
}
</script>

<style lang="scss">

.user-details-wrapper {
    h1 {
        background: #000;
        color: #fff;
        padding: 10px;
        margin-top: 30px;
        display: inline-block;
    }
}

</style>

Screenshot of user list & custom search filter

https://i.sstatic.net/keyh9.png https://i.sstatic.net/ZzpuR.png


Your assistance on this matter would be greatly appreciated!

Answer №1

To implement dynamic routing in your Vue.js application, you can utilize the concept of Dynamic Route Matching. Check out more details about it here.

Start by adding a route to your Vue router configuration:

const router = new VueRouter({
  routes: [
    // Define dynamic segments with a colon
    { path: '/user/:id', component: User }
  ]
})

A dynamic segment is identified by a colon (:). Once a route matches, you can access the value of dynamic segments using this.$route.params within any component.

In your Single User component, make an AJAX call in the mounted hook:

mounted() {
    axios.get("https://jsonplaceholder.typicode.com/users/" + this.$route.params)
    .then(res => console.log(res))
}

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

How to detect internet connection in any screen using React Native?

I'm facing confusion regarding how to display my customDialog when there is no Internet connection in my app. Currently, I have successfully shown my customDialog only in the LoginScreen. However, I want to display it from different screens, not just ...

At what point should you invoke db.close() while utilizing cursor.forEach()?

When working with .toArray(), it is common practice to include db.close() within the callback function. For example: db.collection('grades').find(query).toArray(function(err, docs) { if (err) throw err; console.dir(docs); db.close(); }); ...

Could data be transmitted from a Vue application to another one?

On my web page, I have implemented two separate Vue apps. Due to the presence of Google ads scattered throughout the page and Vue's limitations on script tags within instances, I am unable to combine them. I am looking for a method similar to using p ...

Divide data into an HTML table and merge it with header information

My HTML form contains an interactive HTML table where users can add/delete rows. I am sending this data to a Google Sheet and need to store the row information with corresponding header details. Each time a user submits the form, a new row is added to the ...

Working with Typescript to map and sort the key values of a new datasource object

Managing a large datasource filled with objects can be challenging. My goal is to rearrange the order of objects in the array based on new values for each key. Whenever a new value for a key is found, I want the corresponding object to move to the top of t ...

Tips for updating CSS styles for multiple innerHTML elements using a JavaScript for loop

<div id="test"></div> <script type="text/javascript"> window.names=["jin kazama", "nina williams"]; window.values=[25, 37]; len=names.length for (var i = 0; i < len; i++) { document.getElementById('test').innerHTML+ ...

Tips for assigning unique non-changing keys to siblings in React components

I've been searching for a solution for more than an hour without success. The structure of the data is as follows: const arr = [ { id: 1, title: 'something', tags: ['first', 'second', 'third'] }, { id: 2, t ...

Concerns regarding rendering HTML and drawing in Node.js

Having an issue where node.js is serving an html file with an SVG drawing. The index.html features a chart similar to the line chart found at http://bl.ocks.org/mbostock/3883245 Whenever I try to serve the index.html through the express server, I end up ...

Is it possible to change button behavior based on input values when hovering?

Currently, I am attempting to create a webpage where users can input two colors and then when they press the button, a gradient of those two colors will appear on the button itself. <!doctype html> <html> <head> <script src=&apos ...

What could be causing the lack of response from PHP Ajax?

In the midst of tackling my college project, I find myself working on a webpage that is designed to showcase City and temperature information. To accomplish this task, I am delving into the realm of AJAX in order to dynamically update the temperature at sp ...

Utilize Tailwind CSS in React to dynamically highlight the active navigation item on click

Check out my navigation bar code: <nav className="bg-white shadow dark:bg-gray-800"> <div className="container flex items-center justify-center p-6 mx-auto text-gray-600 capitalize dark:text-gray-300"> <Link ...

Tips for dividing an array based on a defined regex pattern in JavaScript

I want to split a string of text into an array of sentences while preserving the punctuation marks. var text = 'This is the first sentence. This is another sentence! This is a question?' var splitText = text.split(/\b(?<=[.!?])/); split ...

Defining optional parameters in TypeScript

Currently, I am working on implementing strong typing for a flux framework (specifically Vuex). Here is my current code: const actions = { first(context: Context, payload: string) { return doSomething(context, payload); }, second(context: Context) { r ...

The Controller's ActionResult methods are not successfully collecting form data sent through an ajax request

I'm facing an issue with my purchase form where the purchase_return object in the controller is not receiving any data. It seems to be getting productId as 0 and productNm as null. Can someone help me figure out what's causing this issue? Here&a ...

Is it possible to insert a second hyperlink into a JavaScript-occupied anchor?

Check out my reference page at: To change the content in a 'containerarea' div, I am utilizing Dynamic Drive's "Dynamic Ajax" script. Below is an example of the anchor code used: <a href="javascript:ajaxpage('videos-maintenance/app ...

How to manage multiple controllers for the same template in AngularJS?

I am facing a requirement where a single page needs to display a lot of different data, all within one vertical-scrolling page. To manage this, I have implemented collapsible divs on the page controlled by ng-if to efficiently handle the DOM elements. In ...

An empty array is being returned from a mongoose function call

I'm currently working on a project that involves fetching random values from MongoDB using mongoose and storing them in an array. However, I am facing an issue where the array appears to be empty outside the function: exports.Run = (req, res) => { ...

Tips for adjusting the margin of a print document in a printTask?

Is there a way to achieve a borderless print? Currently, my printed output has a border around it. I would like the image to start at the top left corner without any borders. I attempted to set a negative margin to the print-style box, but it resulted in ...

Utilizing visual representations for "symbol" within eCharts4r

I have been exploring the use of the "image" option for the symbol parameter in a tree chart with eCharts4r. Despite trying multiple methods, I am struggling to assign a unique image to each node in the tree instead of using a universal one. However, my a ...

A method for extracting URL parameters based on the matching route path

Is it possible to parse a given URL string in relation to the match.path value? For instance, if the current route is: <Route path="/some/path/:type" /> To obtain the type parameter of the current URL, one can simply use match.params.type ...