Transmitting a Custom JS Object via Vue Router

Stuck! I’ve been hitting my head against the wall for hours trying to figure this out...

Technologies Utilized:

  • Vue (v3.0.0)
  • Vue-Router (v4.0.0-0)
  • Bootstrap (v5.1.1)

The Objective:
I have two pages (Home.vue, MetaUpdate.vue) and one component (Document.vue). Home page contains multiple Document components. Upon clicking the "Update" div/button within a Document component, it should route to the MetaUpdate page. The MetaUpdate page needs to receive the entire Doc JS object which is passed down from the Document component through the router.

The Issue:
When passing my custom object as a prop through the router, it seems to interpret it as the string "[object Object]" instead of the actual object. However, when passing the custom object as a prop from parent component to child component, it interprets correctly. So, how do I effectively send props through the router? It's worth mentioning that originally I was successfully passing two Strings through the router, so I'm confused why switching to a custom object caused everything to break.

JavaScript Object:

class Doc {
    constructor(docID, title, status) {
        this.docID = docID;
        this.title = title;
        this.status = status;
    }
}

router.js

import { createRouter, createWebHashHistory } from 'vue-router'

import Home from '../views/Home.vue'
import MetaUpdate from '../views/MetaUpdate.vue'

import {Doc} from '../controllers/data'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/metaupdate/:doc',
    name: 'MetaUpdate',
    component: MetaUpdate
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

export default router

Home.vue
Though there’s more in the file, this much suffices to address the question at hand.

<template>
<div class="col col-12 col-lg-6 in-progress">
    <div class="doc-status">In Progress</div>
        <template v-for="(doc, index) in inProgress" :key="index">
            <Document :doc="doc"></Document>
        </template>
    </div>
</div>
</template>

<script>
import Document from "../components/Document.vue";
import {Doc} from '../controllers/data'
var inProgress = [];
var pending = []
var completed = [];

export default {
    data: function() {
        return {
            inProgress,
            pending,
            completed
        }
    },
    components: {
        Document
    }
}

/***** Temporary Push of Docs *****/
for(let i = 0; i < 5; i++){
    let docA = new Doc(i, 'Progress Document', 'in-progress');
    let docB = new Doc(i, 'Pending Document', 'pending');
    let docC = new Doc(i, 'Completed Document', 'completed');

    inProgress.push(docA);
    pending.push(docB);
    completed.push(docC);
}
/***** Temporary Push of Docs *****/
</script>

Document.vue

<template>
    <div class="doc">
        <div class="doc-title">{{ doc.title }}</div>
        <router-link to="/docviewer" v-if="isInProgress" class="doc-item submit">Submit</router-link>
        <router-link to="/docviewer" class="doc-item preview">Preview</router-link>
        <router-link 
            :to="{  name: 'MetaUpdate',
                    params: {doc: this.doc} }" v-if="isUpdateOrDelete" class="doc-item update">Update
        </router-link>
        <router-link to="/docviewer" v-if="isUpdateOrDelete" class="doc-item delete">Delete</router-link>
    </div>
</template>

<script>
import {Doc} from '../controllers/data'

export default {
    props: {
        doc: {
            type: Doc,
            required: true
        }
    },
    computed: {
        isInProgress() {
            return this.doc.status === 'in-progress';
        },
        isUpdateOrDelete() {
            return this.doc.status === 'in-progress' || this.doc.status === 'pending';
        }
    }
}
</script>

MetaUpdate.vue
Though there’s more in the file, this much suffices to address the question at hand.

<template>
    <div class="tabs">{{ $route.params.doc.title }}</div>
</template>

<script>
import { Doc } from '../controllers/data'

export default {
    props: {
        doc: {
            type: Doc,
            required: true
        }
    }
}
</script>

Answer №1

It is important to note that when passing route parameters, they must be strings as they become part of the URL. Trying to pass an object as a route param will result in it being converted to a string. Consider what you expected the URL to look like when trying to navigate with an object set as the :doc param.

A better approach would be to set the document ID as the parameter and have the receiving route component retrieve the corresponding object based on this ID. One way to achieve this could be:

  • Maintain all documents in a global array shared across components (such as using Vuex).
  • The parent component can provide the doc array to the <router-view>, allowing the route component to find the document by its ID within this array.

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

What is the best way to remove text from a box when a user clicks on it?

After successfully placing G in the selected box upon clicking it, I now want to work on removing it when clicked again. I'm encountering an issue with my current code - can anyone help me identify what's wrong and suggest a solution? Below is ...

An error occurred when trying to set a cookie using Set-Cookie in a react application

Currently, I am immersed in a small project that involves user authentication via email and password before gaining access to their individual profiles. The backend operates on cookies which are established once the correct email and password combination i ...

Verifying user authorization for Microphone access prior to triggering event in React application

I have created a React component featuring a microphone button that operates as follows: OnMouseDown => Initiates audio recording by the user OnMouseUp => Ceases audio recording To elaborate, while the button is pressed down, the user can continue ...

Merge the variables extracted from an array of objects

I need to extract specific data from an array of objects and perform a calculation. For example, the provided data is as follows: const item = [{ "act": "Q", "line": 1, &quo ...

Using JavaScript to disable and re-enable an ASP.NET Timer control

I currently have a webpage built with ASP.Net that includes an ASP:Timer control <asp:Timer ID="TimerRefresh" runat="server" Interval="5000" Enabled="true" OnTick="TimerRefresh_Tick"> </asp:Timer> It is connected to an asp:UpdatePanel on the ...

Distinguishing Between server.listen() and app.listen() in Google Apple Engine

I am currently working on a NodeJS + Express application. While running it locally, I have the following code: const port = 3001; server.listen(port, () => { console.log(`App listening on port ${port}`); }); However, when deploying to GAE, I switch ...

Include the clicked link into the text input area using Ajax or Jquery

Hey there, I'm just starting out with jquery and ajax so please be patient with me. Below is a snippet of my script that fetches branch names from the database asynchronously: $(document).ready(function () { $("#pickup").on('keyup' ...

What are the steps to resolve the "undefined cannot read property push" error in Node.js?

While attempting to learn Nodejs, I created a simple app. However, when I run "nodemon index.js" in the command prompt, I encountered the following error: TypeError: Cannot read property 'push' of undefined The app crashed and is now waiting for ...

An easy way to attach a Contextmenu to a specific element

I have implemented a scrolling feature for one of the div elements in my Application. Inside this div, there is a templated table with over 100 rows. Users are able to add or delete rows using a contextMenu. The contextMenu offers 4 options - AddTop, AddB ...

Error message encountered in PHP due to an undefined index

My goal is to add items from a form to a table named products. The form layout can be seen here: https://i.stack.imgur.com/f9e08.png The "Add more suppliers: +" link adds a new row to the form when clicked. The corresponding script for this action is as ...

I possess a JSON object retrieved from Drafter, and my sole interest lies in extracting the schema from it

Working with node to utilize drafter for generating a json schema for an application brings about too much unnecessary output from drafter. The generated json is extensive, but I only require a small portion of it. Here is the full output: { "element": ...

Can you target an 'input' field that is within a component conditionally rendered using 'v-if'?

Imagine this vue.js template code: <div v-if="y===0"> <input ref="textbox">{{textbox}}</input> </div> In the scenario where y is data retrieved asynchronously, Is there a way to direct focus to the 'input' element onc ...

Refreshing content with Ajax when the back button is clicked

Hey everyone, I've been working on an ajax site and I'm having trouble getting the content to reload when the back button is clicked. I'm using Dynamic Drives ajax content script along with a script that changes the URL onclick and a popstat ...

Instructions on how to determine if a client is a "desktop terminal"

So here's the deal: I have a suspicion about thin clients accessing my website. Is there a way to test if a client is a thin client without causing it to lag with JavaScript animations? I want to provide a simplified version of the site for these clie ...

Using Next.js to pass fetched data as props to components

I am currently working on integrating a leaflet map into my Next.js project. The map display is already functioning with predefined latitude and longitude in the component. However, I now need to show data retrieved from my API as the longitude and latitu ...

Choose a specific option from the dropdown menu using a URL parameter

After reviewing this code snippet: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> // <![CDATA[ $(document).ready(function() { // Parse your query parameters here, and assi ...

ways to incorporate searching within JSON data using AJAX and jQuery in JavaScript

My search box needs to have JSON data appended into it. Below is the HTML code: <input type="search" id="merchantName" name="merchant" placeholder="enter merchant name"></input> I have JSON data containing merchant names that I want to appen ...

the router is having trouble choosing the right function

When attempting to log in a user using postman with the URL http://localhost:3000/login, it seems to always trigger the register function instead. The code itself is working fine, but it's just routing to the wrong function. How can I redirect it to t ...

Maintaining Object Position in 2D Transforms

I am trying to create multiple perspective-transformed rectangles in the lower right corner of a canvas by using ctx.transform: ctx.transform(1, 0, -1, 1, 10, 10). My goal now is to adjust the size of the drawing based on a variable scale=n, while keeping ...

Get a Blob as a PNG File

Hope you had a wonderful Christmas holiday! Just to clarify, I am new to JS and may make some unconventional attempts in trying to download my Blob in PNG format. I am facing an issue with exporting all the visual content of a DIV in either PDF or image ...