全局自定义弹框/提示框(Uniapp)
发布于 1 年前 作者 vliang 1099 次浏览 来自 分享

场景:任意页面都可以使用方法的形式唤起弹框/提示框

框架:uniapp+Vue3+vite

第一步:安装依赖 

  npm i [@yck-web](/user/yck-web)/vite-plugin-template-inset     
  该插件在转换的时候使用正则对页面进行自定义弹框的添加
第二步:修改配置vite.config.js, plugins中添加插件(位置需要放在uni()方法前面)

  import uni from "[@dcloudio](/user/dcloudio)/vite-plugin-uni";
  import vitePluginTemplateInset from "[@yck-web](/user/yck-web)/vite-plugin-template-inset";

  plugins: [
     vitePluginTemplateInset(["<DialogMessage ref='DialogMessage'></DialogMessage>"]),
     uni(),
  ],
第三步:编辑自定义组件 DialogMessage/index.vue

<template name="dialogMessage">
  <view class="mask" v-if="show">
    <view class="content">
      <view class="title">系统升级</view>
      <view class="hint">为了给您提供更好的体验<br />系统已升级<br />快去试试看吧!</view>
      <van-button class="jump-btn" @click="handleToMini" type="primary" size="large">
        去使用
      </van-button>
    </view>
  </view>
</template>

<!--  自定义全局弹框 -->
<script setup lang="ts">
import { ref } from "vue";

let show = ref(false);

const open = () => {
  show.value = true;
};
const close = () => {
  show.value = false;
};

const handleToMini = () => {
  uni.showToast({
    icon: "success",
    title: "成功",
    duration: 3000,
  });
  close();
};

//暴露open和close方法
defineExpose({
  open,
  close,
});
</script>
<style lang="scss" scoped>
.mask {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.6);
  z-index: 99999;
  padding: 20rpx;
}
.content {
  width: 100%;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border-radius: 32rpx;
  padding: 40rpx 20rpx;
  .title {
    font-size: 38rpx;
    margin-bottom: 20rpx;
  }
  .hint {
    font-size: 24rpx;
    margin-bottom: 16rp;
    text-align: center;
  }
  .jump-btn {
    width: 100%;
    background: $theme-color;
    border-radius: 48rpx;
    color: #ffffff;
    cursor: pointer;
    text-align: center;
    margin-top: 40rpx;
  }
}
</style>
第四步:main.js全局注入

  import DialogMessage from "@/components/DialogMessage/index.vue";

  app.component("DialogMessage", DialogMessage);
第五步:页面使用

<template>
  <view class="home-page">
    <van-button class="jump-btn" @click="handleClick" type="primary" size="large">
      打开全局弹框
    </van-button>
  </view>
</template>

<script lang="ts" setup>
import { getCurrentInstance } from "vue";
const instance = getCurrentInstance() as any;

const handleClick = () => {
  console.log("handleClick", instance?.ctx?.$refs);
  instance?.ctx?.$refs.DialogMessage.open();
};
</script>

效果如下:

1 回复
回到顶部