Vue事件总线打造全局计数器

问题描述 投票:0回答:0

我有几张带有快速添加按钮的产品卡片。以及导航栏上的购物车项目计数器。每次我将产品添加到购物车时,我都想将购物车项目计数器增加 1。但是,只有当我单击相同的产品卡时,计数器才会增加。当我点击另一张产品卡时,计数器从 0 重新开始。任何指针都会有很大帮助。

这是我的代码: 导航栏.js:


export default {
  name: 'Header',
  },
  data() {
    return {
      cartItemCount: 0,
    }
  },
  methods: {
    //assigning the value
    increase_cart_count(val) {
      this.cartItemCount = val;
    }
  },
    created() {
    eventBus.$on("increase_cart_count", this.increase_cart_count);
  },
  destroyed() {
    // Removes Event Bus listener upon removal
    // of template from DOM.
    eventBus.$off("increase_cart_count", this.increase_cart_count);
  }

};

quickAdd.js:

import { eventBus } from "@utilities/vue";
export default {
  data() {
    return {
      cartCounter: 0,
    }
  },
    methods: {
      async quickAddToCart() {
        try {
          this.cartCounter = this.cartCounter + 1; //increasing the cart counter by 1
          eventBus.$emit("increase_cart_count", this.cartCounter);
        }
        catch (error) {
          console.log(error);
         }
    },
};

快速添加模板:

<button
      @click.stop.prevent="quickAddToCart"
    >
      <span>Quick Add</span>
    </button>```
vue.js vue-component event-bus
© www.soinside.com 2019 - 2024. All rights reserved.