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

Regular expressions for identifying operands and operators in a calculator application implemented with JavaScript

I am currently working on a JavaScript project to create a basic calculator. I am in need of a way to validate each item in an array of operands (sequences of digits) and operators (+, -, *, /, ** for power). I have managed to create regex patterns for di ...

There was an issue with retrieving the image URL from the source, causing an error message to display: "

I encountered an error while trying to access my product. Here is the error message https://i.stack.imgur.com/fTmL0.png It seems that the image URL from the sanity database cannot be rendered, even though it worked fine in the tutorial I was following. I ...

When a variable is used, the .sort() method does not effectively organize the elements

When working with Nodejs and mongoose queries, I encountered an issue with using the .sort() method dynamically based on user input. While it works fine when hardcoded, I want to use a variable to determine the sorting order. However, when attempting to do ...

Fixed Navigation - Employing stickUp.js extension

* { box-sizing: border-box; } body { margin: 0; padding: 0; font-weight: 500; font-family: 'Helvetica Neue', sans-serif; } main {} .bckgrnd { background-position: center center; background-repeat: no-repeat; background-attachment: ...

Vue's push() method is replacing existing data in the array

I'm currently facing an issue where I am transferring data from a child component, Form, to its parent component, App. The data transfer is functioning correctly, however, when attempting to add this data to the existing array within the App component ...

Export default does not actually yield a function; rather, it returns an object

I recently developed a function that is responsible for importing a script from a specified source, calling its exported function, and handling the returned result. To simplify things, I have streamlined the code to focus solely on returning the result. co ...

Cross-Origin Resource Sharing - redirecting to the page that is being retrieved by a subsequent GET request

My web page makes AJAX requests using JQuery $.ajax to load content. However, if the user session expires, re-authentication is required. When a user is not authenticated, two GET requests are sent to the website: one with the requested URL in the AJAX (o ...

What is the best method to determine the mean score by utilizing the ID values obtained from API responses?

These are the responses retrieved from the API: const attractions = [ {"id": 1,"name": "drive on avenue"}, {"id": 2, "name": "diving"}, {"id": 3,"name": "visiting ma ...

Sending a jsp page for review at specified intervals

Using the setTimeout method, I attempted to achieve this. I passed a variable containing time as an argument, but the setTimeout method is only taking the initialized value of that variable and not the updated value fetched from the database. Below is the ...

Error: Unable to locate module '@material-ui/lab/TabContext' in the directory '/home/sanika/Desktop/Coding/React/my-forms/src/Components'

Hello everyone! I recently started working with ReactJs and I'm currently facing an issue while trying to implement TabContext using the material UI library in React. Upon debugging, I suspect that the error might be related to the path configuration. ...

Failing to retrieve the file instance upon completing the upload process to cloudinary using nestjs

I am attempting to retrieve the secure file URL provided by Cloudinary after successfully uploading the asset to their servers. Although I can upload the file to Cloudinary, when I try to view the response using console.log(res), I unfortunately receive &a ...

The issue with Angular 2's Parameterised router link component not fully refreshing

I'm trying to figure out how to show a set of images when I click on a specific menu item. The menu structure looks like this: <ul id="demo23" class="collapse"> <li> <a [routerLink]="['image-gallery','Picasso ...

Issue with Yeoman webapp generator and Gulp, encountering error when using Gulp-jade package

I'm encountering some difficulties integrating jade with yeoman's gulp webapp generator. The watch task is functioning properly, but when I attempt to build the project, I encounter the following error: stream.js:94 throw er; // Unhandled ...

Is there a way to apply styles to a checkbox's child element depending on the checkbox's state without relying on ternary operators within Styled Components?

I am currently working on styling this component using Styled Components, but I feel like my current approach is a bit of a hack. What would be the best practice for incorporating Styled Components to style this component effectively? If I were to use Pla ...

Different ways to modify the color and thickness of a variable in HTML5 with either JavaScript or CSS

I am currently working with a JavaScript file where I have a variable defined as follows: var nombre = document.getElementById('nombre').value; The 'nombre' variable corresponds to an element in an HTML file: Nombre: <input type=" ...

Dealing with a unique key error in a loop while using React and Google

I've implemented a react-google-maps component that successfully retrieves data from various locations. However, I'm encountering an error message in the console: Warning: Each child in a list should have a unique "key" prop. I made s ...

The data from the Subscribe API call is gradually loading within the ngOnInit() function

When using Angular 8, I am experiencing slow data retrieval when making API calls in the ngOnInit() function. The issue arises when trying to pass this data as @Input from one component module to another - it initially comes through as undefined for a minu ...

Use CSS specifically for codeigniter viewpage

I am unsure if it is possible, but I would like to load CSS and JavaScript within a view page instead of on include.php. Currently, the CSS file is loading on include.php and it is working correctly. What I want to achieve now is to load it directly inside ...

Tips for correctly mapping a shuffled array in React/Next without triggering a hydration mismatch error

I've been working on a Next.js website and I'm trying to display a randomized list of famous quotes. To achieve this, I'm using lodash to shuffle the array of quotes and then mapping them onto the page. import { useMemo } from 'react&ap ...

The error code 405 (Method Not Allowed) occurs in Ajax when the action field is empty or identical to the current page

Special thanks to @abc123 for sharing the code below in one of their posts: <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> </head> <body> <form id="formoid" a ...