Utilizing Vue JS to pass props from various routes to a shared component

Currently, I am working on developing a menu application using Vue JS. As per the advice given to me, it is suggested that I only need to use one component if the styling remains consistent throughout. This implies that I need to incorporate dynamic data into the application. Each menu or submenu will consist of 3 to 4 menu links. In my quest for finding a solution to pass variables along with data to a component, I stumbled upon 'props'. However, I encountered a challenge while trying to send props from different routes to the same component and determine the route being used in order to load the appropriate props into the HTML.

I have attempted to load props into a template, and this process worked smoothly. Nevertheless, the task of sending and replacing prop values within the same section of HTML remains something that eludes me.

 { path: '/list', component: List, props: { url: 'www.google.com' } }
<template>
    <div class="container">
        <h1>Welcome</h1>
        <div class="row">
            <div class="col-md-6">
                <router-link to='/weed'>Weed</router-link>
            </div>
            <div class="col-md-6">
                <router-link to='/stuff'>Stuff</router-link>
            </div>
            <div class="col-md-6">
                <router-link to='/joint'>Joint</router-link>
            </div>
            <div class="col-md-6">
                <router-link to='/edibles'>Edibles</router-link>
            </div>
        </div>
    </div>
</template>

The <router-link> needs to be dynamic based on the current route, so that it can load different menu items accordingly.

My objective is to create a menu that displays varied route links depending on the active route.

Answer №1

If you're looking to implement Programmatic Navigation and handle query parameters, I suggest the following approach:

router.push({ path: 'register', query: { plan: 'private' } })

For your specific application needs, consider using the code snippet below:

<div class="col-md-6"
     @click="$router.push({ path: '/edibles',
             query: { url: 'www.google.com', other: 'etc' }})"
 >Edibles</div>

To access these query parameters in the component you navigate to, use $route.params.url in templates and this.$route.params.url in other parts of your Vue component.

Make sure to also refer to https://router.vuejs.org/guide/essentials/navigation.html for more information.

In response to a comment, I recommend sticking with Programmatic Navigation:

router.push({ name: 'user', params: { userId } })

You can then pass these parameters as props to the component like this:

    const User = {   
    props: ['id'],   
    template: '<div>User {{ id }}</div>' 
} 
const router = new VueRouter({   
    routes: [     
        { path: '/user/:id', component: User, props: true }      
    ] 
})

Remember to include props: true in your routes definition!

Answer №2

Incorporate parameters from your route into props within your component and utilize a watcher to respond to any changes in the route. You can either use a state management system like Vuex to access specific parameter data or directly make use of the parameters.

Usage:

router.push({ path: '/user/${userId}' })

then

watch: {
  $route(to, from) {
    // implement reaction logic
  }
}

and/or

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

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

Identifying a Malformed URI in JavaScript

In JavaScript, it is considered a best practice to use certain patterns to detect errors instead of solely relying on try-catch blocks. One easy way to do this is by using TypeError: if (typeof foo !== "number") { console.log("That ain't a number!" ...

What is the best way to pause the display of dynamic search outcomes in React?

I am currently working on developing a dynamic search results workflow. While I have successfully managed to render the results without any issues, I am facing a challenge in toggling them off when all input is deleted from the search bar. When typing begi ...

Creating a visually appealing gantt chart in React Native using the react-google-charts library - here's how!

These are the current packages I am using: react-google-charts 1.5.5 react 16.0.0-beta.5 react-native https://github.com/expo/react-native/archive/sdk-22.0.1.tar.gz I am currently working on rendering a Gantt Chart and you can find an example here and a ...

Tips for incorporating dynamic parameters/variables into templates displayed using ng-bind-html or a custom directive (within ng-repeat)

EDIT: I have created a solution sample based on the initial answer. However, I am open to further suggestions and would appreciate any help in filling the gaps in my knowledge (please refer to the comments). plnkr.co/edit/mqGCaBHptlbafR0Ue17j?p=preview OR ...

sorting in React table not functioning properly for computed column

I have a column titled 'EV/Resource ($ per oz)' that appears to not sort correctly in my react table. Instead of sorting in ascending or descending order, it randomizes the table sort. I'm unsure if I am handling this as a "calculated column ...

Utilizing ReactJS and PHP in Harmony

I'm currently facing issues with establishing communication between a fetch call in React and a PHP script running on my MAMP server. Unexpectedly, I am encountering errors that I am unable to troubleshoot effectively. This snippet depicts the code ...

Generating meta tags in a web scraping tool within a front-end application using AngularJS

Running an AngularJS web app entirely on the client side presents a challenge when it comes to adding html meta tags for the FaceBook scraper. These meta tags need to be rendered from the server, without relying on client-side JavaScript. Currently, I&apo ...

Accurate date and time depiction at a high resolution using JSON and JavaScript

Is there a standardized method for displaying high-resolution timestamps in JSON and/or JavaScript? It would be ideal to have support for at least 100 ns resolution, as it would simplify the server code (due to the 100 ns resolution of the .NET ...

Guide to merging two endpoints in express.js to create a single endpoint

I currently have 2 existing endpoints named /balance and /transactions. What is the most effective approach to create a new endpoint called /balance-and-transactions without having to refactor the existing code? For example: a('/balance', () =&g ...

Encountering an error with an undefined callback argument within an asynchronous function

I encountered an issue while working with the viewCart function. I have implemented it in the base controller and am calling it from the home controller. However, I am facing an error where the callback argument in home.js is showing up as 'undefined& ...

RegEx not triggering Mongoose hooks

When performing queries on my mongo collections, I am attempting to call specific hooks for them. DispatchRequest.findOneAndUpdate({user_name:"umesh"},{email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdac8 ...

Create HTML content dynamically with JavaScript and then utilize AngularJS to interpret and render it

I am creating an HTML table that looks like this: <table id="#webappname"> <tr ng-repeat="data in d"> <td>1 {{data}}</td> <td>2 hey !</td> </tr> </table> To create this, I am using a ...

navigating a pointer graphic within a container

I've been working on creating a sniper game, but I've run into an issue with moving the sniper image inside the div. My main objective is to change the image to the sniper image when the mouse hovers over the div. Here's what I have tried so ...

Is it practical to extract the page type/name from the CSS of the selected tab?

My website has multiple tabs on a single page and I want to integrate Google Analytics code. However, since all the tabs are part of the same page, I need a way to track which tab the user is interacting with. Would using CSS to check for the selected tab ...

Avoid losing focus on href="#" (preventing the page from scrolling back up to the top)

Is there a way to prevent an empty href link from causing the page to scroll up when clicked? For example, if I have: <a href="#">Hello world</a> And this "Hello world" link is in the middle of the page. When clicked, the URL would look like ...

I am unable to access Angular $scope in the HTML Template, although I can view it in the console log

I have been following some online tutorials and using the angularjs-template to start learning Angular. However, I am facing an issue where the page (html template) is not updating with the controller. It seems like there is a problem in how I've set ...

Error: Scheme is not a valid function call

Currently, I am attempting to implement user registration functionality in a Node.js application using MongoDB. However, I encountered this error: var UtenteSchema = Scheme({ TypeError: Scheme is not a function Below is my model utente.js: cons ...

How to add suspense and implement lazy loading for a modal using Material-UI

Currently, I am implementing <Suspense /> and lazy() to enhance the performance of my project. While everything seems to be working smoothly, I have observed some minor changes in DOM handling that are causing me slight confusion. Consider this scen ...

Is there a way to execute numerous queries upon the loading of a functional component with UseEffect, and then display the results within the render method

I've created a functional component that loops through an array on load to run async queries and populate a new array for display in the render method. import React, { useEffect, useState, useContext } from 'react'; import { AccountContext ...

Ways to ensure Vue retrieves data from the database whenever a specific event occurs

I have individual buttons next to each row, with unique data entries in the database. When clicking on a button, I want specific information to appear in a Bootstrap Modal. However, I am facing challenges ensuring that Vue updates correctly with each click ...