VUE フレームワーク Vue3 はグローバル イベント バスを使用してデータを転送します-----VUE フレームワーク

import mitt from 'mitt';
// 这个会创建一个对象emitter
// 把它当作全局事件总线对象即可
export default mitt();

「my」から my をインポートします。

// これによりオブジェクトエミッタが作成されます

// グローバル イベント バス オブジェクトとして扱うだけです

デフォルトのmitt()をエクスポートします。

<template>
    <User></User>
</template>

<script>
// 导入全局事件总线对象
import emitter from "./utils/event-bus.js";
import User from './components/User.vue';
// 引入组合式API生命周期钩子函数
import { onMounted } from "vue";
export default {
  components: { User },
    name : "App",
    setup(){
        // 导入生命周期mounted
        onMounted(() => {
            emitter.on('event1',showInfo);
        });
        function showInfo(user){
            alert(`姓名${user.name}年龄${user.age}`);
        }
        return {showInfo};
    }
}
</script>

<style>

</style>

<テンプレート>

    <ユーザー></ユーザー>

</テンプレート>

<スクリプト>

//グローバルイベントバスオブジェクトをインポートする

「./utils/event-bus.js」からエミッタをインポートします。

'./components/User.vue' からユーザーをインポートします。

//結合された API ライフサイクル フック関数を導入します

「vue」から { onMounted } をインポートします。

デフォルトのエクスポート {

  コンポーネント: { ユーザー }、

    名前:「アプリ」、

    設定(){

        //マウントされたライフサイクルをインポートします

        onMounted(() => {

            エミッター.on('イベント1',showInfo);

        });

        関数 showInfo(user){

            alert(`名前${user.name}年齢${user.age}`);

        }

        {showInfo} を返します。

    }

}

</script>

<スタイル>

</スタイル>

<template>
    <button @click="triEvent">触发</button>
    <button @click="remove()">解除所有绑定</button>
    <button @click="removeEvent1()">解除event1绑定</button>
</template>

<script>
import emitter from "../utils/event-bus.js";
export default {
    name : "User",
    setup(){
        function triEvent(){
            emitter.emit("event1",{name:"Jack",age:30})
        }
        function remove(){
            // 清除所有
            emitter.all.clear();
        }
        function removeEvent1(){
            emitter.off('event1');
        }
        return {triEvent,remove,removeEvent1};
    }
}
</script>

<style>

</style>

<テンプレート>

    <button @click="triEvent">触発</button>

    <button @click="remove()">すべてのバインディングを削除</button>

    <button @click="removeEvent1()">event1 のバインドを解除</button>

</テンプレート>

<スクリプト>

「../utils/event-bus.js」からエミッタをインポートします。

デフォルトのエクスポート {

    名前:「ユーザー」、

    設定(){

        関数 triEvent(){

            エミッター.emit("イベント1",{名前:"ジャック",年齢:30})

        }

        関数削除(){

            // すべてクリア

            エミッタ.all.clear();

        }

        関数removeEvent1(){

            エミッタ.off('イベント1');

        }

        戻り値 {triEvent,remove,removeEvent1};

    }

}

</script>

<スタイル>

</スタイル>

おすすめ

転載: blog.csdn.net/2201_75960169/article/details/135182163