vue3使用sweetalert2替代默认的alert/confirm框

安装

#运行时依赖 package.json的dependencies
npm install sweetalert2 --save

#开发时依赖 package.json的devDependencies
npm install sweetalert2 --save-dev  

 新建utils/sweetalert2.js

import swal from "sweetalert2";

export const swal2 = {
    confirm: function (title, text, callback) {
        swal.fire({
            title: title,
            text: text,
            showCancelButton: true,
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
            confirmButtonText: "确定",
            cancelButtonText: "取消",
        }).then((result) => {
            if (result.isConfirmed && callback) {
                callback();
            }
        });
    },
    showErrorMsg: function (title) {
        swal.mixin({
            toast: true,
            showConfirmButton: false,
            timer: 3000,
        }).fire({
            icon: "error",
            title: title,
        });
    },
    showSuccMsg: function (title) {
        swal.mixin({
            toast: true,
            showConfirmButton: false,
            timer: 3000,
        }).fire({
            icon: "success",
            title: title,
        });
    },
    showWaringMsg: function (title) {
        swal.mixin({
            toast: true,
            showConfirmButton: false,
            timer: 3000,
        }).fire({
            icon: "warning",
            title: title,
        });
    },
};

 使用

<script setup>
import { swal2 } from "../utils/sweetalert2.js";

// swal2.showErrorMsg("error");
// swal2.showSuccMsg("succ");
// swal2.showWaringMsg("waring");
swal2.confirm("确定删除吗?", "删除后不可恢复", function () {
  console.log("已删除");
});
</script>
<template>
  <div class="about">
    <h1>This is home page</h1>
  </div>
</template>

 

 

 

posted @ 2022-12-28 16:32  carol2014  阅读(129)  评论(0编辑  收藏  举报