deadsimple/vueeventbus

使用简单的事件总线创建两个独立 Vue 组件之间的 Deadsimple 通信

安装量: 1,557

依赖者: 0

建议者: 0

安全: 0

星标: 0

关注者: 1

分支: 0

开放问题: 0

语言:JavaScript

类型:magento2-module

1.1.1 2020-09-30 13:09 UTC

This package is auto-updated.

Last update: 2024-09-29 05:22:24 UTC


README

Latest Stable Version Total Downloads License

Deadsimple Vue 全局事件总线 Magento2 Composer 库

请注意:事件总线不是解决所有跨组件通信问题的方案。但确实有很多场景,使用 Vuex 或其他状态管理框架对于你想要完成的任务来说过于复杂。这里的任务是两个分别加载在页面不同部分的 Vue 组件之间的通信。

关于 Vue 事件总线更多信息可以在这里找到

如果你想了解更多关于如何在 Magento 2 中使用 VueJS 的信息,可以查看这个仓库

安装

使用 composer 安装模块:composer require deadsimple/vueeventbus

用法/示例

让我们从一个用例开始;在你的产品详情页面上,你想要在产品标题中添加一个按钮,按钮上写着:“添加到愿望单”。这个按钮需要将产品保存到愿望单中。愿望单可以从你页面顶部的导航中访问,你希望显示一个实时计数器,当点击“添加到愿望单”按钮时,计数器会增加。但是,你如何让这两个完全独立的组件相互通信呢?这就是事件总线发挥作用的地方。

让我们创建以下两个文件 wishlist-button.vuewishlist-header-link.vue

⚡️⚡️⚡️

wishlist-button.vue

<template>
    <div>
       <button @click="addToWishlist">Add to Wishlist</button>
    </div>
</template>
<script>
define([
    'Vue',
    'VueEventBus',
], function (Vue, EventBus) {

    Vue.component('wishlist-button', {
        template: template,
        methods: {
            addToWishlist() {
                // You probably want to save the product in a wishlist collection somewhere, but I'm leaving this out in this example
                
                EventBus.$emit('addedToWishlist'); // Transmit a signal 
            }
        }
    });

});
</script>

⚡️⚡️⚡️

wishlist-header-link.vue

<template>
    <a href="#">
        My whishlist ( {{ counter }} )
    </a>
</template>
<script>
define([
    'Vue',
    'VueEventBus',
], function (Vue, EventBus) {

    Vue.component('wishlist-header-link', {
        template: template,
        data() {
            return { 
                counter: 0
            }
        },
         mounted() {
            this.getCount();
            
            const self = this;
            
            // Listen to the Event Bus for the transmitted signal set in the other file and fire a 
            EventBus.$on('addedToWishlist', function() {
             this.counter = this.counter + 1;
            })
         }
    });

});
</script>

⚡️⚡️⚡️

在这个示例中,你可以看到我们在两个文件中都包括了 VueEventBus,这就是这两个元素之间事件通信的粘合剂,我们从一个文件发出信号到另一个文件,并在另一个文件中根据事件进行操作。