首先,在 uniapp 中创建一个名为 GlobalPopup 的自定义组件。

在 GlobalPopup.vue 文件中,编写以下代码:

<template>
  <div class="global-popup" v-show="visible">
    <div class="global-popup__mask" @click="close"></div>
    <div class="global-popup__content">
      <slot></slot>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    close() {
      this.$emit('update:visible', false)
    }
  }
}
</script>

<style scoped>
.global-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.global-popup__mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.global-popup__content {
  background-color: #fff;
  padding: 20px;
  border-radius: 10px;
  text-align: center;
}
</style>

这个组件包含两个部分:遮罩层和弹窗内容。遮罩层用来防止用户在弹窗出现时操作页面,弹窗内容可以通过插槽来传递。

在需要使用全局弹窗的页面中,可以直接使用 GlobalPopup 组件。例如,在 App.vue 中添加以下代码:

<template>
  <div>
    <global-popup :visible="showPopup" @update:visible="showPopup = $event">
      <div>这是一个全局弹窗</div>
    </global-popup>
    <button @click="showPopup = true">打开全局弹窗</button>
  </div>
</template>

<script>
import GlobalPopup from '@/components/GlobalPopup.vue'

export default {
  components: {
    GlobalPopup
  },
  data() {
    return {
      showPopup: false
    }
  }
}
</script>

在这个例子中,我们将 GlobalPopup 组件插入到 App.vue 的模板中,并将 showPopup 变量绑定到 visible 属性上。当用户点击打开按钮时,showPopup 变量会被设置为 true,从而显示弹窗。当用户点击遮罩层或关闭按钮时,showPopup 变量会被设置为 false,从而关闭弹窗。

在微信小程序中,需要在 pages.json 文件中注册 GlobalPopup 组件:

{
  "pages": [
    {
      "path": "pages/index/index",
      "usingComponents": {
        "global-popup": "@/components/GlobalPopup"
      }
    }
  ]
}

然后,在 index.wxml 文件中添加以下代码:

<global-popup visible="{{showPopup}}" bind:update:visible="showPopup = $event.detail">
  <view>这是一个全局弹窗</view>
</global-popup>
<button bindtap="openPopup">打开全局弹窗</button>

在 index.js 文件中,编写以下代码:

Page({
  data: {
    showPopup: false
  },
  openPopup() {
    this.setData({
      showPopup: true
    })
  }
})

这个例子和 H5 的例子类似,都是将 showPopup 变量绑定到 GlobalPopup 组件的 visible 属性上,然后通过 openPopup 方法来控制 showPopup 变量的值,从而打开或关闭弹窗。

通过这种方式,我们可以轻松地在 uniapp 中创建一个自定义的全局弹窗,并且可以在 H5 和微信小程序中使用

用 uniapp 写一个自定义的全局弹窗 不需要页面引入 用js可以控制打开或关闭兼容h5和微信小程序

原文地址: https://www.cveoy.top/t/topic/fg3X 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录