Navigating with Vue.js using programmatic methods while passing props

I am working with a Vue component that includes a prop called 'title' like this:

<script>
export default {
  props: ['title'],
  data() {
    return {
    }
  }
}
</script>

After completing a specific action, I need to programmatically navigate to the component. Is there a way to set the prop value while routing the user programmatically? I am aware of creating a link in this manner:

<router-link to="/foo" title="example title">link</router-link>

But is it possible to achieve something similar to the following?

this.$router.push({ path: '/foo', title: 'test title' })

UPDATE:

Following some suggestions, I have updated my route as shown below:

   {
      path: '/i/:imageID',
      component: Image,
      props: true
    }

And the navigation now looks like this:

this.$router.push({ path: '/i/15', params: {title: 'test title' }})

However, even after these changes, my Image component (template - displayed below) still does not display the title.

<h1>{{ title}}</h1>

Is there any possible reason for this issue?

Answer №1

It's important to utilize params in Vue router.

this.$router.push({ name: 'foo', params: {title: 'test title' }})

Remember to specify the name when using this.$router.push, as it won't function properly with just the path.

Additionally, configure the route to accept params as props.

{path: "/foo", name:"foo", component: FooComponent,  props: true}

For more information on setting props, check out the official documentation.

Answer №2

The documentation for vue-router makes it clear that params only function with the name property and not with path.

// To make params work, set props: true in the route definition
const userId = 123
router.push({ name: 'user', params: { userId }}) // -> /user/123
// Using path as shown below will NOT work
router.push({ path: '/user', params: { userId }}) // -> /user

If you need to use path, either include the params in the path itself or utilize query like the examples below:

router.push({ path: `/user/${userId}` }) // -> /user/123

// Utilizing query to get /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})

Answer №3

Encountering a similar issue with children routes defined in the router. Below is the snippet from router.js showing how children routes are linked to named views.

<router-view name="create"></router-view>
<router-view name="dashboard"></router-view>

router.js

{
  path: "/job",
  name: "Job",
  component: () => import("./views/JobPage"),
  children: [
    {
      path: "create",
      name: "JobCreate",
      components: {
        create: JobCreate
      }
    },
    {
      path: ":id",
      name: "JobConsole",
      components: {
        dashboard: JobConsole
      }
    }
  ]
},

However, when trying to pass props from 'create', vue-router is unable to capture the required dynamic route matching for 'JobConsole':

this.$router.push(
  {
    name: "Job",
    params: {
      id: this.ID_From_JobCreate
    }
  })

Answer №4

Dealing with a similar issue, it seems like the existing answers may be outdated. After referring to the latest updates on https://github.com/vuejs/router/blob/main/packages/router/CHANGELOG.md#414-2022-08-22, it appears that the method of pushing routes has changed:

this.$router.push({ name: 'foo', params: {title: 'test title' }})

It seems this approach is no longer supported. Instead, I resorted to using Vuex, which offers speed and simplicity in my implementation. https://vuex.vuejs.org/guide/

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

Can you explain the mechanics behind the animation of the upvote button on steemit.com?

Behold the upvote button of steemit.com: <span class="Icon chevron-up-circle" style="display: inline-block; width: 1.12rem; height: 1.12rem;"> <svg enable-background="new 0 0 33 33" version="1.1" viewBox="0 0 33 33" xml:space="preserve" xmlns=" ...

Assign a property to an array of objects depending on the presence of a value in a separate array

Looking to manipulate arrays? Here's a task for you: const arrayToCheck = ['a', 'b', 'c', 'd']; We have the main array as follows: const mainArray = [ {name:'alex', code: 'c'}, ...

Utilizing Node and Express to transform an array into a "Object" Map

For my latest project, I decided to build a web application using Node Express for the backend and Vue for the front end. While working on it, I encountered an issue where an array in an object was being converted to a map when sent to Express via jQuery. ...

What could be causing this conflicting behavior with the logical "and" operator?

const {DEMO, PORT, LOCAL} = process.env; const socketAddress = (DEMO & LOCAL)? `http://${hostname}:${PORT}`: `wss://${hostname}`; When DEMO is false, PORT is undefined, and LOCAL is true The hostname being used is http://9f9cbf19.ngrok.io I verified ...

Adjust the color of the glyphicon icon within a date and time picker dropdown component

I decided to implement the bootstrap datetimepicker using this gem and utilized the following HTML code: <div id="custom-dates" style=" clear:both;"> <div class="container"> <div class="row"> <div class='col-md-3 col-xs-3' ...

Tips for implementing a button redirection to a different page using React

I am facing an issue with a component that includes a function onClick in its Class.propTypes: onClick: PropTypes.func Within another component, I have used this particular component multiple times to populate a page. Each instance of these components con ...

Is it possible to change the text of a scrollspy dropdown to a default text when it is not actively tracking any items?

I am new to Vue and currently implementing Bootstrap Vue Scrollspy (view example here). My sticky dropdown is tracking all referenced content and updates with the current section in view. You can check out my code sample here. Is there a way to set the d ...

React Component Functions for Export and Import

Currently working on a webapp built with React. My main component is defined in App.js, while I have another subcomponent responsible for creating buttons, like the logout button generated by renderLogoutButton(). But now, I want to reuse this function in ...

Expanding circle with CSS borders on all edges

My goal is to create a background reveal effect using JavaScript by increasing the percentage. The effect should start from the center and expand outwards in all directions. Issue: The percentage increase currently affects only the bottom and not the top ...

The Functionality of Accordions

I have created a responsive accordion script that functions smoothly and allows for easy access to content within each drawer. Unlike many accordions, this one does not cause issues with positioning after opening. The code I am using includes a toggle acti ...

Creating a database using Angular2+ in CouchDB can be achieved by following these steps

I have been attempting to set up a database in couchdb using angular2+. My goal is to create a button that, when clicked, will initiate the creation of the database. However, I keep encountering an error message. "ERROR Error: Uncaught (in promise): H ...

Organize your file dependencies efficiently using NPM

I'm currently part of a medium-sized team working on a large front-end application. Up until now, we have been using requirejs and AMD modules to manage our project with approximately 500 files. However, we recently decided to transition to commonjs a ...

Creating bidirectional binding between a Vue.js instance and a custom native web component: A step-by-step guide

Here is an example showcasing a custom web component called my-input. The goal is to establish a binding between the value attribute of this custom input component and the email attribute of a Vue instance. (Please note that this example may require Chrome ...

What exactly is the significance of the </< in THREE.Camera.prototype.lookAt</<()?

After experimenting with THREE.js for a while, I came across something peculiar: When using Firefox and opening the developer console to type camera.lookAt (assuming your camera is named camera), it displays function THREE.Camera.prototype.lookAt</< ...

Validating optional fields in React

My registration form includes the following fields: Name Email Password Confirm password Optional field Select role (student, professor, secretary) Here's what I'm trying to achieve: If I want to create a user with a student role, the optional ...

Node.js C++ addons provide accessors for interacting with Node.js from native

How can I implement setter and getter for a global variable 'X' in a C++ extension for Node.js? I am encountering issues with undefined 'x' while using the getter and setter methods. Currently working on a program involving Accessors ...

Vue 3 - Cascading Property Updates throughout the Component Tree

I have a Vue 3 application set up in the following structure: +---------------------+ | Component | | +-----------------+ | | | Child Component | | | +-----------------+ | +---------------------+ The components are structured as follows: my-com ...

The problem of undefined icons in Material UI's Stepper StepLabel

Having some trouble incorporating a custom Step Label Icon within the nodes of the Stepper Component provided by Material UI. I want to add an icon to each circle, similar to what is shown in this Material UI demo: https://i.sstatic.net/WLOcS.png However, ...

Issue with jQuery hide() function in Internet Explorer 9

I need help with creating a hidden div that becomes visible when a user clicks a link. The code I have works in FF / IE7 / IE8 but not in IE9, where the div is always visible without any content. Any advice is appreciated! <script> $(document).r ...

Scrolling seamlessly on websites with a single page

I am developing a single-page website that uses different section IDs instead of multiple pages. It's functioning properly, but I want to implement smooth scrolling to the sections rather than just statically jumping to them on the page. Jsfiddle: ht ...