欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

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

最编程 2024-10-19 09:57:52
...

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-后面的变量值。

推荐阅读