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

The usage of event.returnValue has been phased out. It is recommended to utilize the standard event.preventDefault()

Here's the code snippet I'm working with: <script> $(document).ready(function () { $("#changeResumeStatus").click(function () { $.get("{% url 'main:changeResumeStatus' %}", function (data) { if (data[&apos ...

Experience a seamless transition as the background gently fades in and out alongside the captivating text carousel

I have a concept that involves three background images transitioning in and out every 5 seconds. Additionally, I am utilizing the native bootstrap carousel feature to slide text in synchronization with the changing background images. Solving the Issue ...

Activate $digest when a variable is modified by a node.js function

I am currently working on developing an application using node-webkit and AngularJS. Everything was going smoothly until I tried to make Angular watch over a "legacy variable" using the method outlined in this answer, which led to an Error: [$rootScope:inp ...

The state in a functional component in React fails to update after the initial axios call

Issue : The value of "detectLanguageKey" only updates after selecting the language from the dropdown twice. Even after selecting an option from the dropdown for the first time, the detectLanguageKey remains empty and is only updated on the second selectio ...

Retrieving information from an ajax array in PHP

I am currently attempting to retrieve an array of data using AJAX on the PHP side, but I am facing difficulties in accessing the values in PHP. Here is my JavaScript code snippet: console.log(obj); $.ajax({ method: 'POST', url: '/in ...

It appears that the SignalR proxy is not defined

Why is $.connection.connectionhub showing as undefined? I am using webform. <script src="/scripts/jquery-1.6.4.min.js"></script> <!--Reference the SignalR library. --> <script src="/scripts/jquery.signalR-2.2.1.min.js">< ...

Using RTK Query to store data in a Firebase Realtime Database

Currently, I am facing an issue while trying to retrieve data from a Firebase Realtime Database using RTK Query. The code in this section is throwing an error because the return value is incorrect. If anyone has experience with this particular issue, I wou ...

AngularJS application: the button requires two clicks to activate

In my attempt to develop a simple CRUD app using AngularJS, I encountered an issue. The initial step involves clicking a button that fetches data from a REST API and populates an array. This array is then iterated using ng-repeat to generate Bootstrap card ...

The issue with Bootstrap Vue scrollspy arises when trying to apply it to dynamic data. Upon closer inspection, it becomes evident that the elements are activating and highlighting one by

In my application built with Vue, content is displayed based on the component type (Header, Text, Image) in a JSON file. I am looking to implement scroll spy functionality specifically for the Header component containing headings. I have attempted to use ...

The modal in Bootstrap V5 refuses to hide using JavaScript unless the window method is utilized

Currently in the process of developing a react application and utilizing standard bootstrap. The command to display a modal and switch to one is functioning properly; but, the command to hide the modal does not work unless I establish it as a property on t ...

The babel-preset-es2016 plugin is in need of the babel-runtime peer dependency, however it seems that it

While I am aware that npm no longer automatically installs peer dependencies, why do I still receive a warning after manually installing them? ➜ npm install babel-runtime -g /usr/local/lib └─┬ <a href="/cdn-cgi/l/email-protect ...

Setting the width of a div element dynamically according to its height

Here is a snippet of my HTML code: <div class="persoonal"> <div class="left"></div> <div class="rigth"></div> </div> This is the CSS code I have written: .profile { width: 100%;} .left { width: 50%; float: le ...

Tips for leveraging async and await within actions on google and API integration

Currently, I am developing an Actions on Google project that utilizes an API. To handle the API calls, I am using request promise for implementation. Upon testing the API call, I observed that it takes approximately 0.5 seconds to retrieve the data. Theref ...

The double click feature on Vuetify's v-data-table is not functioning as expected

I've been working with a v-data-table component. As per the official documentation, it supports a dblclick:row event. However, when I tried using it, nothing happened. (The click:row event works just fine.) The vuetify version I'm using is th ...

Incorporating various language URLs in Next.js using next-i18n-next functionality

Thinking about using the next-i18next internationalization library. Check out next-i18next on GitHub Curious about how to change the language in the path of my URL. For example: /about-us /over-ons -> takes you to the Dutch version of the about us p ...

Getting a variable from outside of the observable in Angular - a step-by-step guide

I have an Observable containing an array that I need to extract so I can combine it with another array. this.builderService.getCommercialData() .subscribe( data=>{ this.commercialDetails = data; this.commercialDetailsArr ...

Navigating a Vue.js project with multiple brands and a variety of component types: Tips for success

I am interested in developing a Vue.js project that incorporates multiple brands. Each brand will be determined by the domain and will share the same routes, but display different components in the views. Some components may be shared between brand views ...

What is the process for populating dropdown options from state?

I've been struggling to populate a select element with options based on an array in state. Despite trying various methods, the code snippet below seems to be the most detailed (I'm still getting familiar with React after taking a break for a few ...

The characteristics that define an object as a writable stream in nodejs

Lately, I've been delving into the world of express and mongoose with nodejs. Interestingly, I have stumbled upon some functionality that seems to work in unexpected ways. In my exploration, I noticed that when I create an aggregation query in mongoos ...

Vue's asynchronous handling of props

I have a method that triggers an asynchronous call. methods: { computeCoveragePercentage() { this.calculateCompletionBySubject(1).then((percent) => { return percent; }); }, This method computes a percentage based o ...