Ⅰ. eventBusとは?
簡単に言えば、どのコンポーネントでも、メッセージ(パラメーター)を渡したい->任意のコンポーネントに特定のロジックを実行します。
Ⅱ. vue3 での eventBus の使い方
- vue3 には eventBus がないので自分で書く必要がありますが、とても簡単です。
ステップ 1 (eventBus コンテナー)
- src ディレクトリに bus フォルダーを作成し、自分で作成した bus.js を格納します。
- bus.js を書く => 3 つの (subscribe、unsubscribe、publish) 関数をクラス プロトタイプにバインドします。
// bus.js
class Bus {
constructor() {
this.list = {
}; // 收集订阅
}
// 订阅
$on(name, fn) {
this.list[name] = this.list[name] || [];
this.list[name].push(fn);
}
// 发布
$emit(name, data) {
if (this.list[name]) {
this.list[name].forEach((fn) => {
fn(data); });
}
}
// 取消订阅
$off(name) {
if (this.list[name]) {
delete this.list[name];
}
}
}
export default new Bus;
- サブスクライバー (on)、関数をリストに入れる => パブリッシャーを待つ (emit)、パラメーターを渡して呼び出す;
- 関数はオブジェクトであるため、メモリアドレスは変更されておらず、サブスクライバ (on) コンポーネントで引き続き実行されます。
ステップ 2 (加入者)
- comA.vue で購読します。
- サブスクリプションは関数を保存するだけで、公開されるまで実行しません。
<template>
<div>
{
{ name }} --- {
{ age }}
</div>
</template>
<script>
import {
ref , onUnmounted} from 'vue';
import Bus from '../bus/bus.js';
export default {
setup() {
const name = '张三';
const age = ref(18)
Bus.$on('addAge',({
num })=>{
age.value = num; })
//组件卸载时,取消订阅
onUnmounted( () => {
Bus.$off('addAge') } )
}
}
</script>
- コンポーネントを離れるとき (onUnmounted) は、登録済みおよびサブスクライブ済みの関数の配列を削除して、さらに多くの関数を保存しないようにします。
ステップ 3 (パブリッシャー)
- comB.vue で公開します。
- サブスクリプションを呼び出してパラメーターを渡します。
<template>
<button @click="fabu">发布</button>
</template>
<script>
import Bus from '../bus/bus.js';
export default {
setup() {
function fabu(){
Bus.$emit('addAge',{
age:'19'});
}
}
}
</script>
- パブリッシュ後、サブスクライバーのコンポーネントが実行されます。対応するサブスクリプションとパブリケーションの名前は同じである必要があることに注意してください。