Vue3 中的5种常见的组件传值方式,Vue3事件总线(无需插件)

1,087次阅读
没有评论

Vue3 中常见的组件传值方式:

  1. Props:这是 Vue 中最常见的组件传值方式,即在父组件中定义 prop 并将数据传递给子组件。
  2. Event Bus:可以通过事件总线在两个组件之间进行通信,即定义一个中央事件处理器,父组件和子组件通过它进行通信。
  3. Provide/Inject:可以在父组件中提供数据,并在子组件中注入这些数据,从而实现组件传值。
  4. Slots:可以在父组件中嵌入子组件,并在子组件中使用插槽传递数据。
  5. Vuex:Vuex 是 Vue 官方推荐的状态管理工具,也可以用于组件之间的数据通信。

以上是 Vue3 中常见的组件传值方式,你可以根据实际需求选择合适的方式进行组件传值。

事件总线的示例(其他传值方式网上文章很多):

(在vue2中我们可以直接new Vue创建一个空组件作为事件处理中心并使用其$emit和$on订阅和发布事件,Vue3官方推荐使用vue3-eventbus插件,可我觉得就这个事,没必要多安装一个插件吧)

首先,需要创建一个事件总线的类(这是一个单例类,我们可以在任何需要的地方通过new获得唯一实例):

// EventBus.js
export default class EventBus{
    static instance;

    constructor(){
        if(EventBus.instance instanceof EventBus){
            return EventBus.instance;
        }

        this.events = {};

        EventBus.instance = this;        
        return EventBus.instance;
    }

    emit(eventName, data) {
        if (this.events[eventName]) {
            this.events[eventName].forEach(function(fn) {
                fn(data);
            });
        }
    }
    on(eventName, fn) {
        this.events[eventName] = this.events[eventName] || [];
        this.events[eventName].push(fn);
    }

    off(eventName, fn) {
        if (this.events[eventName]) {
            for (var i = 0; i < this.events[eventName].length; i++) {
                if (this.events[eventName][i] === fn) {
                    this.events[eventName].splice(i, 1);
                    break;
                }
            };
        }
    }
}

然后,在组件中订阅和发布事件:

// ComponentA.vue
import EventBus from '@/util/EventBus';

// 发布事件
export default {
  methods: {
    handleClick() {
      new EventBus().emit('event-name', payload);
    },
  },
};

// # 最后,你可以在另一个组件中监听事件:
// ComponentB.vue
import EventBus from '@/util/EventBus';

export default {
  mounted() {
    new EventBus().on('event-name', (payload) => {
      // do something with the payload
    });
  },
};

这样,就可以在不同的组件之间通过事件总线进行自由通信了。

facingscreen
版权声明:本站原创文章,由 facingscreen2023-02-12发表,共计1395字。
转载说明:本文为搜栈网原创文章,除特殊说明外皆由CC-4.0协议发布,转载请注明出处,如有帮助欢迎打赏。
评论(没有评论)
验证码