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

What is the best way to fully eliminate the Pixi renderer, stage, and all associated assets

I am currently faced with a challenge of mounting and unmounting a Pixi stage using React without relying on react-pixi. Upon re-mounting the component, I encounter the following error: Uncaught Error: Resource with name "cupCake.png" already exists i.ad ...

How do I delete an attached file in an input document? (Firefox)

Is there a way to smoothly remove an attachment selected in the <input type="file"> element? In Firefox, removing an already selected attachment can be tricky. Simply deleting the name or trying to click open may not work. An additional solution mi ...

What is the best way to retrieve elements from this JSON data?

Currently, I am developing a command line interface to display random quotes. I have found an API to fetch quotes from, but the issue is that the JSON response is returned as an array. [{"ID":648,"title":"Jeff Croft","content":"<p>Do you validate ...

What is the best way to independently trigger changes in multiple copies of a Component?

Is there a way to use a computed property to trigger a boolean value within a component without impacting other copies of the same component? I have multiple instances of this component and want each one to trigger independently based on specific conditi ...

Is it possible to make a form field inactive based on another input?

I need help with disabling certain form fields until other fields are filled in. You can check out an example of what I'm trying to achieve here: https://jsfiddle.net/fk8wLvbp/ <!-- Bootstrap docs: https://getbootstrap.com/docs --> <div ...

Issues with displaying HTML5 audio player in iOS Chrome and Safari browsers

My html5/jquery/php audio player is working well on desktop browsers, but when I tried testing it on iOS, all I could see was a grey track bar. I suspect that the controls are hidden behind the track bar because sometimes the associated file starts playing ...

Using .NET Core 3.1 along with Vue, Axios, and incorporating the use of [ValidateAntiForgeryToken

I've spent the entire day working on this and researching as much as I can, but I have been unsuccessful in getting it to function. Despite comparing my implementation with the Microsoft documentation and various answers on Stack Overflow, none of th ...

Using jQuery's .each() method to iterate over a JSON object may only display the

Running into some trouble with jQuery.each(). I'm pulling JSON data from another PHP file and trying to display a specific key value from it. This is the JavaScript code I have: <div class="row" id="fetchmember"> <script type="text/javasc ...

Exploring the potential of Framework7 in Single Page Applications: optimizing performance by preloading

I'm currently working on developing a web application using Framework7. Framework7 offers routing APIs for navigating between HTML pages. It seems that the pages are loaded dynamically through AJAX requests. I am curious if it is possible to preload ...

Is the npm mqtt module continuously running but not performing any tasks?

I'm relatively new to the world of JS, node.js, and npm. I am attempting to incorporate a mqtt broker into a project for one of my classes. To gain a better understanding of how it functions, I installed the mqtt module from npm. However, when I tried ...

displaying specific items in a vue list based on status conditions

Here is my Vue code snippet (and a working fiddle): https://jsfiddle.net/he26tn53/: <div id="app"></div> new Vue({ el: "#app", template:`<h2>People:</h2><span @click="showOnlyEnabled = !showOnlyEnable"> toggle enabled< ...

Steps to transfer selected autocomplete value ID to data attribute using jQuery

I am working on a project where I need to store the State ID in my database instead of the State Name. Currently, I am using an autocomplete query to select the State. How can I pass the selected State's respective ID to the data-attribute of the inpu ...

using JavaScript to strip away content following .jpg

var lochash = "#http://www.thepresidiumschool.com/news_image/102%20NRD_7420.jpg&lg=1&slide=0"; I am looking to eliminate or modify the content that comes after .jpg. ...

Adjust the height of a div using jQuery animate based on the amount of text within

I have created a basic animation feature where users can click on an expanding box. I am looking for a solution that does not involve using a plugin. Currently, the code looks like this: $('#one').css("height", "22"); $('#t1').cli ...

What is the best way to maintain the highlighting of a clicked navigation button in CSS?

.custom-highlight { display: inline; font-weight: 500; font-size: 15px; } .item-list { border: 1px solid #b1b8c9; color: $color-grey-light; font-size: 14px; display: inline-block; margin-right: 8px; padding: 5px 20px; border-radius: 4p ...

Combine multiple key values from an array of objects into a single array

I have a set of key and value pairs that I need to filter based on whether the values are in an array or not, and then combine them into a single array. const holiday_expenses = { food: [{name: "abc", place: "xyz"}], travel: [{name: ...

Extracting a particular element from a sophisticated auto-complete DOM structure by drilling down into the $scope

After spending a significant amount of time trying to solve this problem, I find myself at a dead end. The simplicity of using jQuery makes me reconsider Angular, but perhaps my approach is flawed. In this scenario, the DOM structure looks like this: < ...

Creating a tool to display mouse coordinates as a pointer on an HTML5 canvas

I'm struggling with mouse coordinates while working on canvas in HTML5. My approach involves using JavaScript for drawing on the canvas. Below is my current code to track the mouse pointer within the canvas: $('#canvasID').mousedown(functi ...

Do I have to include reject() in the executor when using promises in express.js?

If we choose not to handle rejection, is it necessary to include the reject parameter in the promise executor? For example: new Promise((res) => { res(a); }) ...

Updating a table in Javascript after deleting a specific row

Is there a way to automatically reindex rows in a table after deleting a row? For example, if I delete row 1, can the remaining rows be reordered so that they are numbered sequentially? function reindexRows(tableID) { try { var t ...