What is the best way to transmit data via $router.push in Vue.js?

I am currently working on implementing an alert component for a CRUD application using Vue.js. My goal is to pass a message to another component once data has been successfully saved. I attempted to achieve this by passing the data through $router.push like so:

this.$router.push({path: '/', query: {alert: 'Customer Added'}})
. However, instead of accessing the data in the desired component, it seems to be getting passed into the URL.

The component responsible for saving the data is Add.vue:

<template>
<div class="add container">
<Alert v-if="alert" v-bind:message="alert" />
<h1 class="page-header">Add Customer</h1>
<form v-on:submit="addCustomer">
    <div class="well">
        <h4>Customer Info</h4>
        <div class="form-group">
            <label>First Name</label>
            <input type="text" class="form-control" placeholder="First Name" 
            v-model="customer.first_name">
        </div>
        <div class="form-group">
            <label>Last Name</label>
            <input type="text" class="form-control" placeholder="Last Name" 
            v-model="customer.last_name">
        </div>
    </div>
    <div class="well">
        <h4>Customer Contact</h4>
        <div class="form-group">
            <label>Email</label>
            <input type="text" class="form-control" placeholder="Email" v-model="customer.email">
        </div>
        <div class="form-group">
            <label>Phone</label>
            <input type="text" class="form-control" placeholder="Phone" v-model="customer.phone">
        </div>
    </div>

    <div class="well">
        <h4>Customer Location</h4>
        <div class="form-group">
            <label>Address</label>
            <input type="text" class="form-control" placeholder="Address" v-model="customer.address">
        </div>
        <div class="form-group">
            <label>City</label>
            <input type="text" class="form-control" placeholder="City" v-model="customer.city">
        </div>
        <div class="form-group">
            <label>State</label>
            <input type="text" class="form-control" placeholder="State" v-model="customer.state">
        </div>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</template>

<script>
import Alert from './Alert'
export default {
name: 'add',
data () {
    return {
    customer: {},
    alert:''
    }
},
methods: {
    addCustomer(e){
        if(!this.customer.first_name || !this.customer.last_name || 
!this.customer.email){
            this.alert = 'Please fill in all required fields';
        } else {
            let newCustomer = {
                first_name: this.customer.first_name,
                last_name: this.customer.last_name,
                phone: this.customer.phone,
                email: this.customer.email,
                address: this.customer.address,
                city: this.customer.city,
                state: this.customer.state
            }
            this.$http.post('http://slimapp.dev/api/customer/add', 
            newCustomer)
                .then(function(response){
                    this.$router.push({path: '/', query: {alert: 'Customer 
            Added'}})

                });
            e.preventDefault();
            }
            e.preventDefault();
            }
            },
            components: {
             Alert
            }
            }
            </script>

            <!-- Add "scoped" attribute to limit CSS to this component only 
            -->
            <style scoped>
            </style>

This is the alert component, Alert.vue:

<template>
<div class="alert alert-warning alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">&times;</span></button>
{{message}}
</div>
</template>

<script>
export default {
name: 'alert',
props: ['message'],
data () {
return {

}
}
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

Finally, we have the component where the alert is intended to be displayed, Customers.vue:

<template>
<div class="customers container">
<Alert v-if="alert" v-bind:message="alert" />
<h1 class="page-header">Manage Customers</h1>
<table class="table table-striped">
  <thead>
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>Email</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="customer in customers">
      <td>{{customer.first_name}}</td>
      <td>{{customer.last_name}}</td>
      <td>{{customer.email}}</td>
      <td></td></tr>
  </tbody>
</table>

</div>
</template>

<script>
import Alert from './Alert';

export default {
name: 'customers',
data () {
return {

  customers: [],
  alert: ''

 }
},

methods: {
fetchCustomers(){
  this.$http.get('http://slimapp.dev/api/customers')
    .then(function(response){

      this.customers = (response.body); 
    });
  }
 },
created: function(){
 if (this.$route.params.alert) {
   this.alert = $route.params.alert
 }
 this.fetchCustomers();
},
updated: function(){
this.fetchCustomers();
},
components: {
  Alert
  }
}

If you're facing issues with passing the alert message correctly, one solution could involve revisiting how the data is being passed between components and ensuring proper handling within each component's methods and lifecycle hooks.

Answer №1

Vue-router does not support passing data in the way you are attempting. Instead, you can pass parameters like this:

To define a route:

{ path: '/products/:id/edit', name: 'products.edit', component: ProductForm },

You can then access the parameter using this.$route.params.id

Alternatively, you could use:

this.$router.push({name: 'products.index', params: { id: 1 }})

I recommend adding a GET parameter like ?success=true or displaying an alert using sweetalert before navigating to the new route.

Answer №2

One unconventional approach involves storing the value in store/local_storage, then accessing and clearing it upon loading the destination page.

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 MUI date picker does not display dates earlier than 1900

I am in need of a datepicker that allows users to select dates from the 1850s, however, the mui datepicker only starts from the 1900s. To demonstrate this issue, I have provided a sample code in this codesandbox I am utilizing mui in the remainder of my ...

Customizing the Header Navigation in Vue App.vue Across Various Views

Struggling to find the best approach for managing a header navigation in Vue 2 using Vuex with VueRouter. The main issue is creating a dynamic 'header' type navigation in App.vue. <div id="nav"> <!--Trying to create a dynamic ...

Running a JavaScript animation within an Electron environment

My curiosity lies in developing man-machine interfaces using Electron. Currently, I am experimenting with a Star Trek life signs monitor demo. I came across this code that can be easily customized to create vertical and horizontal movements: http://jsfiddl ...

Which method is optimal for organizing tree categories and linking them to posts, as well as locating posts based on a selected category within a MERN stack

Currently, I am utilizing the MERN stack for my project development. The project involves a tree category structure as outlined below: {id: { type: Number }, parent_id: { type: Number }, name: { type: String }, sub: { type: Boolean }} For ...

jQuery mobile menu: Scroll to content after closing the menu

I am currently working on a project where I am using mmenu for the first time. It's functioning as expected, but there is one particular issue that I would really like to have resolved. Here is the URL: What I am hoping to achieve is that when a men ...

Vue.js HTML file served by an express server

I recently built a Vue application using the CLI and successfully created the necessary dist folder with HTML, JS, and CSS files after running the build command. My next step is to host this app on Heroku using a Node/Express server, but I've encounte ...

Vue Custom Element encountering issues when generating independent JavaScript files in the Dist directory

I recently followed the instructions for registering and utilizing custom elements as outlined here: https://alligator.io/vuejs/custom-elements/ For my project, I am using the standard Webpack template for Vue. After executing the command npm run buil ...

Using Cordova plugman to add the initial platform-specific plugin into the project

Here are the system dependencies: cordova: @7.1.0 plugman: @2.0.0 I am trying to use plugman specifically for installing plugins on a particular platform (such as android). Having reviewed the documentation, I find that the workflow and usage is not en ...

Even after refreshing the page, Chrome stubbornly insists on showing the old data

I've been working on a single-page application where one page triggers server requests every time it loads. After making changes and deploying them, I noticed that the live version of the application was not reflecting the updates. Even though the cha ...

Leveraging @click within dropdown selections - Vue.js 2

Is there a way to implement the @click event in select options? Currently, I have the following: <button @click="sortBy('name')">sort by name</button> <button @click="sortBy('price')">sort by price</button> Th ...

How to toggle code block visibility in Angular's ngOnInit() method

I'm currently analyzing different design patterns to optimize the number of REST calls when implementing a 'save while typing feature'. To provide a general overview, in my ngOnInit() function, I have included the following code snippet (wit ...

What is the method for generating a 2D array in JavaScript when the array's length is unknown?

I'm trying to create a 2D array that groups animals by their first letter of the alphabet. However, the output is not what I expected. I want each letter to have its own sub-array with corresponding animal names. Here's the code I tried: functio ...

Creating fluid motion with a bezier curve in ThreeJS

I am looking to animate a bezier curve in ThreeJS with updating start, end, and control points. Eventually, I will have multiple curves animating simultaneously. What is the most efficient approach to achieve this? When running the code snippet below, you ...

Tips for utilizing the form.checkValidity() method in HTML:

While delving into the source code of a website utilizing MVC architecture, I encountered some difficulties comprehending it fully. Here is a snippet of the view's code: function submitForm (action) { var forms = document.getElementById('form& ...

The filter functionality isn't functioning properly when attempting to filter an array of objects within a Vuex action

I have a collection of objects that is accessed through a getter. I am using this getter inside an action to filter the items, but no matter what I do, the filtering does not seem to work and it ends up returning all the mapped item IDs. filterItems({ gett ...

Having trouble removing a cookie in express?

Seems pretty straightforward. In the /user/login route, I set a cookie as shown below: if (rememberMe) { console.log('Login will be remembered.'); res.cookie('user', userObj, { signed: true, httpOnly: true, path: '/' ...

Could it be that the AmCharts Drillup feature is not fully integrated with AngularJS?

UPDATE: Check out this Plunker I created to better showcase the issue. There seems to be an issue with the Back link label in the chart not functioning as expected. I'm currently facing a challenge with the AmCharts Drillup function, which should a ...

retrieving information from the database and passing it to the controller

I'm in the process of developing a new API with Express, following the MVC architecture. However, I've been facing difficulties getting the data to successfully return from the database access file to the controllers file. Initially, I attempted ...

Issues arise with req.body being undefined when using node.js in conjunction with Express version 4.16.X and Body-Parser version

Recently, I began using node.js to construct a RESTFul API. Currently, my focus lies in inserting data through POST requests with JSON in the body. However, I encountered an issue where the req.body always returned as undefined. Upon investigating further ...

Utilizing Node.js and express to promptly address client requests while proceeding with tasks in the nextTick

I am looking to optimize server performance by separating high CPU consuming tasks from the user experience: ./main.js: var express = require('express'); var Test = require('./resources/test'); var http = require('http'); va ...