uniapp全局监听,页面修改页面 uni.$emit(),uni.on(),uni.off()

文章2023-02-0199 人已阅来源:网络

页面A

<template>
    <view>
        <text>我是任一页面</text>
        <button type="warn" @click="globleEvent">全局事件订阅</button>
    </view>
</template>
 
<script>
    export default {
        methods:{
            globleEvent(){
                //全局事件订阅只要注册的页面都可以收到回调值
                uni.$emit("globleEvent","我是全局事件订阅的调用方法")
            }           
        }
    }
</script>

页面B

<template>
    <view>
       <view>{{title}}</view>
      <view>{{content}}</view>
    </view>
</template>
 
<script>
    export default {
        data() {
            return {
                title:'任二页面初始状态',
                content:"此页面初始内容"
            };
        },
        onLoad() {
         //结束上一次监听
         uni.$off();
            //全局事件订阅,只要订阅了事件就可以收到值
            uni.$on("globleEvent",async (res)=>{
             console.log(res);//我是全局事件订阅的调用方法
             tihs.content = res;
               this.update()
            })
        },
        methods:{
            async update(res){
              //此时可以进行你的主页面的操作,调用某个方法等等
                this.title="被任一页面修改后的"
            }
        }
    }
</script>