Passing props in VueJS is a common task, especially while redirecting to another

I am working with two separate single-file components, each equipped with its own named route. In the Setup.vue component, there is a basic form that gathers and sends data to the Timer.vue component which expects certain props. Is there a way to navigate to a specific route in Vue.js while passing props without including them as URL parameters?

Setup.vue

<script>
export default {
    ...
  methods: {
    startTimer() {
      this.$router.push({
        name: 'timer',
        params: {
          development: this.development,
          inversion: this.inversion,
          stop: this.stop,
          fix: this.fix,
          wash: this.wash
        }
      })
    }
...
}
</script>

Timer.vue

<script>
export default {
  name: 'timer',
    ...
  props: {
    development: { type: Number, required: true },
    inversion: { type: Number, required: true },
    stop: { type: Number, required: true },
    fix: { type: Number, required: true },
    wash: { type: Number, required: true }
  }

router.js

    {
      // I want to avoid having to do this route, instead just /timer
      path: '/timer/:development/:inversion/:stop/:fix/:wash',
      name: 'timer',
      component: Timer,
      props: true
    }

Answer №1

Absolutely, you have the ability to accomplish this task and retrieve the props in the variable shown below:

this.$route.params

However, it's important to note that whenever you refresh the page, any params not present in the URL will be lost. Therefore, this method is most effective when navigating between routes within the application without triggering a full reload.

In similar situations, I tend to utilize query variables instead of params to address the issue. You can opt for this approach or create a child routes tree to better organize your props.

Answer №2

Consider the following suggestion -

this.$router.push({
  name: "timer",
  params: { fix: { type: 1, required: true } }
});

Execute this code after submitting a form. Keep in mind that if a user refreshes the timer page, the route parameters will be lost and you will need to find an alternative solution. If the data can be obtained from an API, it is recommended to make an API call in the created method of the timer page to load the data in case of a page refresh.

Answer №3

In order to provide a comprehensive solution, I would like to present an additional option. The method suggested by Henrique above is a more straightforward approach to accomplishing my initial objective of routing and passing props to the component without relying on route variables at the URL level.

By utilizing Vuex as part of our store, we can store variables in a globally accessible object that can be accessed across different components.

store.js

export default new Vuex.Store({
  state: {
    development: null,
    inversion: null,
    stop: null,
    fix: null,
    wash: null
  }

Setup.vue

export default {
  data() {
    return {
      development: null,
      inversion: null,
      stop: null,
      fix: null,
      wash: null,
      store: this.$root.$store // local pointer to the global store, for efficiency
    }
  },
  methods: {
    startTimer() {
      // commit changes to the Vuex store using a transactional history model
      this.store.commit('development', this.development * 60)
      this.store.commit('inversion', this.inversion * 60)
      this.store.commit('stop', this.stop * 60)
      this.store.commit('fix', this.fix * 60)
      this.store.commit('wash', this.wash * 60)
      this.$router.push({
        name: 'timer'
      })
    },

Timer.vue

export default {
  name: 'timer',
  data() {
    return {
      state: this.$root.$store.state
    }
  },
  computed: {
    // mapping local values to global state values
    development() {
      return this.state.development
    },
    stop() {
      return this.state.stop
    }
...

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 steps can I take to generate a JSON array with this unique format?

The data I received from my angular form is in the array format: [{"name":"Rose","number":"+919224512555"},{"name":"smith","number":"+91975555224"}]. The data represents a dynamic table with columns for name and number. I need to convert the array above i ...

How to efficiently pass dynamic props in Next.js persisting layoutuciary

When setting up a persistence layout, I utilize the getLayout function on each page as shown below: import { Layout } from 'hoc'; const Page = () => { return ( <div>hello</div> ); }; Page.getLayout = function getLayout(pa ...

Adjust the color of TextareaAutosize component using mui in React

Just starting out with React and getting acquainted with mui components. Experimenting with setting the color of a TextareaAutosize mui component using this code: import * as React from 'react'; import TextareaAutosize from '@mui/material/T ...

Record the user inputs displayed within the console

Is there a way to retrieve the form values in the console? Currently, when I try to do so, I am only seeing an empty object. <div class="cont"> <v-form ref="form" class="form sign-in" ...

Creating a chart with multiple series in canvas js through looping

I'm currently working on creating a multi-series chart using Canvasjs. I've encountered an issue where I can't include a loop inside the dataPoints and have had to manually code everything. Is there a way to utilize for loops in this scenari ...

Trigger a popup notification with JavaScript when

Check out this snippet of code: <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/ ...

`Finding the nodejs API route for displaying images from a database`

How can I successfully display an image from the database without getting a string of question marks instead? Click here to see the issue >>> When attempting to directly call the API using the provided link, the following result is returned: {&qu ...

Fix for fixed scrolling in the navigation bar

Having a website that receives traffic from different countries, including Portugal and other non-English speaking places, I decided to add a translation option. However, I encountered an issue with Google's translate feature which displays a banner a ...

Guide to automatically update div with new table rows with the help of Ajax

Can you assist me in updating the div called "table" that contains a table fetching rows from the database? <div id="table"> <h1 id="Requests"> <table></table> </h1> </div> <button id="refresh-btn"&g ...

Two tags attached to four hypertext links

Within my HTML code, I have hyperlinks present on every line. However, I am seeking to eliminate these hyperlinks specifically from "your previous balance" and "your new balance". In the following HTML snippet: <tr *ngFor="let l of statementLines; ...

Combining both the Javascript and PHP components of the Facebook SDK

I recently integrated the JavaScript version of Facebook SDK, but now I'm unsure how to also integrate the PHP version without causing any conflicts. Here are my questions: If I implement the PHP SDK from Facebook, is there a way to detect if the J ...

Challenges with registering on Ajax platform

I'm currently facing an issue with my login/sign up process and I can't seem to figure it out. I have shared a jsfiddle link with the code, but I am struggling to identify the problem. https://jsfiddle.net/Zemanor/fuzrkw16/1/ Whenever I submit ...

Can you explain the technical distinctions between Express, HTTP, and Connect?

const express = require("express") , app = express() , http = require("http").createServer(app) As I observe, these dependencies are commonly used. As far as I understand it, http serves front-end HTML, while express manages server-side Node.js logic. ...

What is the implication when Typescript indicates that there is no overlap between the types 'a' and 'b'?

let choice = Math.random() < 0.5 ? "a" : "b"; if (choice !== "a") { // ... } else if (choice === "b") { This situation will always be false because the values 'a' and 'b' are completely disti ...

Choose carefully when to utilize forkJoin

In a particular scenario, I need an application to generate menus based on specific contexts. Here are the definitions for menuA and menuB: // menuA example from a given source menuA() { return [ { a: 'demo1', b: &apo ...

Unable to utilize jQuery within the NetBeans IDE

Whenever I try to include a jQuery file in Netbeans like this: <script type="text/javascript" src="js/jquery-1.3.2.js"> my code doesn't seem to work. However, when I use the following method: <script type="text/javascript" src="http://ajax ...

JavaScript - memory heap exhausted

Recently, I encountered an issue with my API written in Node.js. The purpose of this API is to read data from a MySQL database, write it into a CSV file, and allow users to download the file once the writing process is complete. Initially, everything was f ...

Issues arise when attempting to include the src attribute within the template tag in a Vuejs and Laravel project

After starting a project with Vuejs and Laravel using Laravel Mix, I encountered an issue. When attempting to split my component into separate files and load them in the .vue file as follows: <template src="./comp.html"></template> &l ...

I'm unable to modify the text within my child component - what's the reason behind this limitation?

I created a Single File Component to display something, here is the code <template> <el-link type="primary" @click="test()" >{{this.contentShow}}</el-link> </template> <script lang="ts"> imp ...

TypeError thrown by Mapbox markers

Looking to incorporate markers into my map using Mapbox. Below is the Angular TypeScript code I am working with: export class MappViewComponent implements OnInit { map: mapboxgl.Map; lat = 41.1293; lng = -8.4464; style = "mapbox://styles/mapb ...