欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > uniapp上如何绑定全局事件总线(引入自定义全局组件例如弹窗)

uniapp上如何绑定全局事件总线(引入自定义全局组件例如弹窗)

2024/10/26 7:23:45 来源:https://blog.csdn.net/qq_42371932/article/details/142910911  浏览:    关键词:uniapp上如何绑定全局事件总线(引入自定义全局组件例如弹窗)

1、在main.js中挂载bus

// main.js
Vue.prototype.$bus = new Vue();
uni.$bus = Vue.prototype.$bus;  // 确保在 uni 上绑定

2、写一个全局弹窗组件

<template><view v-if="visible" class="toast-container"><view class="icon-container"><text class="icon">!</text> <!-- 圆形边框内的感叹号 --></view><text class="toast-message">{{ message }}</text></view>
</template><script>
export default {data() {return {visible: false,message: ''};},created() {this.$bus.$on('showToast', this.showToast);},methods: {showToast(message) {this.message = message;this.visible = true;setTimeout(() => {this.visible = false;}, 2000); // 2秒后自动隐藏}}
};
</script><style scoped>
.toast-container {position: fixed;bottom: 150rpx;left: 50%;transform: translateX(-50%);background-color: rgba(0, 0, 0, 0.7);padding: 10px 20px;border-radius: 5px;text-align: center; /* 文字居中 */z-index: 9999;
}.icon-container {width: 60rpx; /* 圆形的宽度 */height: 60rpx; /* 圆形的高度 */border: 2px solid white; /* 圆形的边框 */border-radius: 50%; /* 使其变为圆形 */display: flex; /* 使用 flexbox 居中内容 */align-items: center; /* 垂直居中 */justify-content: center; /* 水平居中 */margin: 0 auto 5px; /* 圆形和文本之间的间距 */
}.icon {color: white; /* 图标的颜色 */font-size: 24px; /* 图标的大小 */
}.toast-message {color: #fff;font-size: 18px; /* 调整字体大小 */
}
</style>

3、需要的地方引入使用

uni.$bus.$emit('showToast', result.response.data.message);

也可以在easycom中学习uniapp组件的全局引入方式

"easycom": {"^u-(.*)": "@/uni_modules/uview-ui/components/u-$1/u-$1.vue","^my-(.*)": "@/componets/my-$1.vue",}

 其中$1就是my-后面的变量值。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com