How do I send events between router view components in Vue.js?

I'm currently developing an e-commerce platform utilizing vue.js with a backend API. The root component is named Main.vue, consisting of a navigation section using router-link and a main content area displayed by router-view.

Within the Cart.vue route, whenever a user modifies the quantity of a product, I require Cart.vue to emit an event to the root component Main.vue in order to trigger the getCartTotal() function.

Note: Cart.vue is not a child component of Main.vue.

Main.vue :

<template>
  <div>
    <!-- Main content of Main.vue -->
  </div>
</template>
<script>
import VueCookies from "vue-cookies";

export default {
  // methods and functions for Main.vue component
};
</script>
<style>
</style>

And Cart.vue :


<template>
  <div>
    <!-- Main content of Cart.vue -->
  </div>
</template>

<script>
import VueCookies from "vue-cookies";

export default {
  data() {
    return {
      cartData: [],
      emptyCart: false,
      loading: true
    };
  },

  created() {
    this.getCartContent();
  },
  
  methods: {
    // other methods and functions
  
    updateCartQuantity(pkey, pquan) {
      // logic for updating cart quantity
      // triggering getCartTotal() function in Main.vue
    },
  }
};
</script>
<style scoped la>
.cart-product-row {
  /* styling*/
}
#cart-delete {
  /* styling */
}
</style>


In conclusion, the updateCartQuantity() function within Cart.vue should activate the getCartTotal() function in Main.vue.

Answer №1

Instead of reaching for Vuex, consider using a simpler pub/sub technique by creating a basic file that exports a new Vue instance to listen for emitted events:

//bus.js

import Vue from 'vue'

export default new Vue()

In your Main.vue, import the bus like this:

import EventBus from '@/path/to/bus'

In the created hook of Main.vue, set up a listener:

created() {
    EventBus.$on('refresh_cart_total', this.getCartTotal)
}

To trigger the event from your Cart.vue, import the bus again:

import EventBus from '@/path/to/bus'

In Cart.vue, emit the event as needed:

EventBus.$emit('refresh_cart_total')

This creates a simple pub/sub system without the need for Vuex in this scenario.

Bonus Tip:

To enhance reusability, you can define constants within bus.js:

export const REFRESH_CART_TOTAL = 'refresh_cart_total'

Now you can use

import * as CART_CONSTANTS from '/path/to/bus'
and reference these constants like so:

EventBus.$on(CART_CONSTANTS.REFRESH_CART_TOTAL, this.getCartTotal)

and:

EventBus.$emit(CART_CONSTANTS.REFRESH_CART_TOTAL)

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 connect a Jquery plugin to a table within a partial view following an ajax request?

I have a main view that utilizes a partial view to display items in a table format. Main View (Enclosed within a div, it references the Partial View) <div id="divList"> @Html.Action("_list") </div> Partial View (Displaying a list of it ...

jQuery: Managing and modifying values for dynamically generated input elements

Hello, I am currently working with the latest version of jQuery and have a table set up where clicking on the "Add" button appends a row of inputs. My goal is to calculate the total price for each particular product based on keyup events (i.e., qty * price ...

Sending data from HTML and JavaScript to Python

In the process of developing a website that will operate on an embedded device, I am implementing an interface for users to engage with multiple functions on the site. These functions within the HTML interface will communicate with a Python script, which i ...

The utilization of the base64 function leads to an InvalidCharacterError

My goal is to implement the base-64 module method in my node.js + express project. Here is the code snippet: router.get('/list', function(req, res, next) { client.query('SELECT * FROM Document',function(err, row){ if(err) ...

Conceal the Vue router on a webpage

How can I hide the vue-router from my login page? I want to remove the menu on the Login page. Is it possible and how would I achieve that? Here is the code for the Login page: Login <template> <div> <h1>Login</h1> ...

Setting environmental variables throughout your application using create-react-app on the front end

Hey there! I have a simple Todo app with the client using create-react-app and the server running on node. I'm struggling to properly set environment variables across my app. I've placed my .env file in the root directory of the app, which curre ...

How can I properly reset a timeout duration?

I'm currently working with a function that looks like this: function blabla(){ ... setTimeout(() => { //do some stuff }, 10000) } My question is, how can I reset the time of the timeout (10000) if the function was called and ...

Guidelines on Importing Azure App Service Application Settings into VUE

Our Vue app is currently hosted on Azure App Service. In the Azure Portal, we have configured application settings such as VUE_APP_API_ENDPOINT_URL under Settings\Configuration. According to the documentation, these settings become environment variabl ...

Error: Attempting to set the 'display' property of an undefined element, causing the loader to not disappear

I am currently using Brackets to work on a website and I wanted to add a loading page to it. However, I have encountered an issue with the following error message: "Uncaught TypeError: Cannot set property 'display' of undefined". The lo ...

Using Angular to implement floating input labels with typeahead functionality

I recently implemented a style from this source: http://tympanus.net/Development/TextInputEffects/index.html If you want to create an input directive, check out the example on Plunker: https://plnkr.co/edit/wELJGgUUoiykcp402u1G?p=preview While it works p ...

Performing two simultaneous AJAX requests using tokeninput

I've been playing around with the tokeninput plugin and it's been working really well for me. However, I recently came across a new requirement - I need to make two separate ajax calls on the same input bar. Situation: My input bar is as follows ...

Is there a way to utilize ajax to submit a form and upload a file to a spring controller?

I have a form with four fields: file, name, type (as a string), and taskInstanceId. <form> <table id="documentDetailsTable"> <tr> <td>Document Type: </td> <td><select id="documentType" ...

What is the method to implement foreach within a Vue select component?

Is there a way to utilize a Vue loop within a select box in order to achieve the following category and subcategory options layout: +news -sport -international +blog In PHP, I can accomplish this like so: @foreach($categories as $cat ...

Enhance the slider's worth

Hey there, just wanted to mention that I didn't write this code myself. Another person did, and I'm a bit lost trying to figure out how to assign values to the three sliders. I don't want a default value; I want each slider to take its value ...

Django: Comparing the benefits of embedding JavaScript in templates versus loading it externally

My current project involves incorporating JavaScript functionality to allow for commenting without the need to refresh the page. This works seamlessly when I embed the JavaScript directly into the template. However, when I extract the JavaScript code into ...

Employing API Integration with Node.js and AngularJS

Currently in the process of developing a language translating messaging application using Node and Angular. I have decided to utilize the Yandex API since Google Translate is not free. You can find more information about the API at www.yandex.com I am unc ...

Node.js publication date displaying incorrectly

When I post a date to elasticsearch, I typically use Date.now() var unixtime = Date.now(); The output usually looks something like this: 1373508091156 To convert it, I then use the following code: var date = new Date(unixtime*1000); After conversion, ...

Delete particular user inputs following a $.ajax request

I have created a search feature with inputs that allow users to search the database using ajax requests. Unfortunately, I am facing an issue where the response from the server includes the search inputs themselves. This is not what I want. Here's a ...

Click the submit button to display a div element without having to refresh the page

Is it possible to display a spinner for a couple of seconds before the page reloads upon submitting a form? <form class="ready" action="https://link.com" method="post"> <input name="test" type="submit" class="click" value="order"/> </form&g ...

Problem with Snowpack's internal module import paths

While working on a project, I am using npx snowpack build --watch instead of the dev command because of a Flask backend. However, I am facing issues with internal imports, specifically modules importing dependencies like Bootstrap importing Popper. The pr ...