skip to Main Content

So I have my app.js

import { createApp } from 'vue';
import ProductsGrid from './components/ProductsGrid.vue';
import Cart from './components/Cart.vue';
import NavLink from './components/NavLink.vue';
import Navbar from './components/Navbar.vue';

const app = createApp({
  components: {
    'products-grid': ProductsGrid,
    'cart': Cart,
  }
});

app.mount('#app');

my product grid component just lists the items fetched from an api. each item has a "buy" button.
When you press a button, it emits this buy event:


        buy(product) {
            this.$emit('buy', product);
            console.log("buy event triggered on produt "+product.id);
        },

the text and the given product are shown in the console log.

But I want to add them to the cart, which is a separate component. How am I supposed to do that?
I know you can listen to an event in the same component with v-on (or @smth), but this doesn’t work in my case.

The cart component is just this:

addProductToCart(product) {
            console.log(product+" product received by products grid component");
        },

How am I supposed to listen to an event from another component?
Or am I doing it the wrong way?

I’m using these in a laravel project, so these vue components are used in blade templates.

2

Answers


  1. You can use event bus to handle this case

    Create event bus inside main.js

    ...
    export const eventBus  = new Vue();
    ...
    

    In component A.vue (emit event through event bus)

    import {eventBus} from "../main.js"
    
    export default {
      ...
      methods: {
        buy: function(product) {
          eventBus.$emit("buy-product", product);
        },
      },
      ...
    };
    

    In component B.vue (listen event emitted from event bus)

    import { eventBus } from "../main";
    export default {
      ...
      created: function() {
        eventBus.$on("buy-product", (product) => {
          console.log("product received from event bus " + product.id);
        });
      },
      beforeDestroy() {
          eventBus.$off("buy-product");
      }
     ...
    };
    
    Login or Signup to reply.
  2. Vue 3 – Event bus

    From what I see you are using the latest version of Vue.js (3.x).
    As stated here https://v3-migration.vuejs.org/breaking-changes/events-api.html#migration-strategy, the global event bus is removed in Vue 3 (this.$emit is still available for child -> parent communication.

    In order to implement a global Event bus for different components in app to communicate with events, you need an external package such as mitt.
    The implementation is easy if you follow the examples. Hope this helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search