Sending real-time information to Vue parameters and routes

I've recently started working with Vue and I'm facing some challenges. I'm not sure if it's even possible, but I'll pose the question to see what insights the Stack Overflow community can offer.

My query is about storing component data/props for multiple IDs within the data() method of the default export.

For example, {{$route.params.id}} captures the ID from the URL, but I want to know if I can store other data related to different IDs within the Project.Vue file itself. Is it feasible to manage data for 5 distinct IDs in a single file or do I need to create separate files (Project1.Vue, Project2.Vue, etc.) and set them up as individual routes?

I attempted to add bits to the data() method like this:

    data () {
        return {
            msg: 'Projects',
            id: [{ 1: 'hi'}, {2: 'hey'}],
            two: 'project two',
            three: 'project three',
        }
    }

However, referencing 'id' inside the <template> returned the entire object instead of the specific data. I also tried decoupling as suggested here: https://router.vuejs.org/en/essentials/passing-props.html, but couldn't get it to work.

I hope someone can provide clarity on whether my desired approach is achievable. The code snippets used are included below:

index.js

import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/components/Home'
import Contact from '@/components/Contact'
import About from '@/components/About'
import Projects from '@/components/Projects'


Vue.use(Router)

export default new Router({
  routes: [
    {
        path: '/',
        name: 'Home',
        component: Home
    },

    {
        path: '/contact',
        name: 'Contact',
        component: Contact
    },

    {
        path: '/about',
        name: 'About',
        component: About
    },

    {
        path: '/projects',
        name: 'Projects',
        component: Projects
    },

    {
        path: '/projects/:id',
        name: 'Projects',
        component: Projects,
        props: {default: true}
    },

  ]
})

Projects.Vue

<template>
    <div id="projects">
    <h1>{{ header }} {{ $route.params.id }}</h1>
        {{id}}
    </div>
</template>



<script>
    export default {
        name: 'Projects',
        watch: {
            '$route'(to, from) {
                // react to route changes...
            }
        },
        data () {
            return {
                header: 'Projects',
            }
        }
    }
</script>


<style scoped>
</style>

Answer №1

After some exploration, I was able to solve the issue.

To dynamically pass data depending on the ID in the URL, you must create a data object and then within the <template>, you can pass the created object but include $route.params.id inside square brackets. Keep in mind that because the object inside your data() function uses zero index, it's recommended to subtract 1 inside the template. Refer to the code snippet below for a clearer understanding:

<template>
    <div id="projects">
    <h1>{{ msg }} {{ projects[$route.params.id - 1] }}</h1>
    </div>
</template>

<script>
    export default {
        name: 'Projects',
        watch: {
            '$route'(to, from) {
                // respond to route changes...
            }
        },
        data () {
            return {
                projects: [
                    {   id: 1,
                        name: 'First Project'
                    },
                    {   id: 2,
                        name: 'Second Project'
                    },
                    {   id: 3,
                        name: 'Third Project'
                    },
                ]
            }
        }
    }
</script>

<style scoped>
</style>

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

Eslint can cause issues when it comes to declaring types in Typescript

https://i.sstatic.net/qJ4an.png Hey there, I'm currently dealing with this block of code. Every time I try to declare a type, I encounter this error message. Eslint seems to be suggesting that I use a variable instead of returning void. Using //// ...

Assign the value of one dropdown menu based on the selected value of another dropdown menu using PHP

When a selection is made in the first dropdown, I want the values in another dropdown to be populated accordingly. I need to verify the value of the first dropdown with a variable and then populate the options in the second dropdown based on that conditio ...

What specific files from the Kendo core are required for utilizing Mobile and Angular functionalities?

After browsing through similar questions, I couldn't find a solution. Currently, I am experimenting with Kendo (open source core for now) in a Visual Studio Cordova project. Initially, disregarding Cordova, I am focusing on setting up a basic view wit ...

Discovering ways to determine if multiple strings are present within a single string using JavaScript

After writing this function, I noticed it only worked with a single string value. contains(input, words) { let input1 = input.split(' '); for (var i = 0; i < input1.length; i++) { if (input1[i] === words) { ...

Updating On/Off Switch status dynamically

I need help figuring out how to dynamically set a toggle switch button based on a value using Bootstrap. Can anyone assist me in identifying what I might be missing? The variable user.isActive can only have a value of true or false. <td><input i ...

Transform jQuery scroll script into vanilla JavaScript

While I am quite familiar with jQuery, I find myself struggling when it comes to using pure JavaScript. Could anyone provide guidance on how I can convert my jQuery code into vanilla JavaScript? Your help is greatly appreciated! Below is the code that I ...

Exploring the Wonderful World of Styled Components

I have a query regarding styled components and how they interact when one is referenced within another. While I've looked at the official documentation with the Link example, I'm still unclear on the exact behavior when one styled component refe ...

Is it possible to send emails from a local server to Gmail, Yahoo, or Rediff?

Currently, I am developing a feature that allows users to send emails to any recipient including Yahoo and Gmail. Below is the code snippet for my contact form: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1 ...

Having trouble with script tag not loading content in Next.js, even though it works perfectly fine in React

Currently, I am attempting to utilize a widget that I have developed in ReactJS by utilizing script tags as shown below- React Implementation import React from "react"; import { Helmet } from "react-helmet"; const Dust = () => { ...

Discover the route connecting two points. The current maze algorithm is operating at a sluggish

I'm in the process of developing an algorithm to identify the most efficient route between two points within a maze, but I've hit a snag with its current speed. Here's what I've done so far: Auxiliary classes: import { Coord } from " ...

Error: The function $(...).draggable is not recognized" and "Error: The object $.browser is not defined

I encountered an error stating, TypeError: $(...).draggable is not a function. To resolve this issue, I added jQuery as follows: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> < ...

What is the method for accessing an image in JavaScript?

Currently, I am developing a currency converter for a gaming marketplace and I would like the users to be able to generate images using JavaScript. While most of the work is completed, I am facing an issue where the images are not displaying properly and i ...

How can you alter the animation direction of a Bootstrap carousel slide?

Is it possible to create a reverse animation effect for a bootstrap carousel slide without changing the order of slides? 1 2 3 4 to 4 3 2 1 I just want the slides to appear in reverse order, is that achievable? The code snippet looks like this: < ...

Issues with Vuetify not recognizing style adjustments

Trying to modify the design so that buttons display text with capital letters instead of all uppercase. My version of Vue is 3.5.5 I have included src/stylus/main.styl $button-text-transform = 'capitalize' @require '~vuetify/src/stylus/ap ...

Is it feasible to have unique popups for individual textbox edits?

I am experiencing a problem with a popup in Asp.net while using AJAX modalpopup extender. I am wondering if it is feasible to display one type of popup when the user modifies certain textboxes, and another type of popup for the remaining textboxes. I beli ...

What are some creative ways to customize and animate the cursor or caret within an input field?

Just to clarify, I am working with React and Material-UI. I have a task at hand where I need to modify the appearance of the caret within an input element by adding an animation to it. I have managed to change its color using caret-color and set a default ...

Troubleshooting the defects in the string-to-json module functionality

I am dealing with string data var str2json = require('string-to-json'); var information={ "GTIN" : "GTIN 3", "Target Market" : "Target Market 3", "Global Location Provider Name(GLN) 3" : "Global Locati ...

Obtaining the Camera's Position Relative to the Origin in Three.js

The wording of this question might be unclear, but I'm struggling to phrase it concisely. Here's the scenario: there is a perspective camera in the scene along with a mesh. The mesh is positioned away from the origin of the axis. The camera is ...

Efficient method for handling numerous AJAX requests

I have a web application that currently makes 14-15 AJAX calls to various APIs. The issue is that the combined time it takes for all the AJAX calls to complete is significantly longer than when I individually type each API's URL into the browser. Cur ...

Organizing numerical values within for loops

I'm having trouble determining prime numbers and non-prime numbers. When I follow the logic of looping through numbers from 2 to 100, it makes sense for primes. However, when I start at 0 and loop by y + itself, it seems counterintuitive to me. For ex ...