Vue2.0 自定义toast组件

612 阅读1分钟

第一步:toast组件 Toast/index.vue文件,按照通用组件封装,可以针对success和error提示做单独的样式处理

<template>
    <div class="toast-wrapper" v-show="visible">
        <div class="toast-success">
            <img src="@/assets/imgs/error.png" class="error-icon" v-if="type === 'error'" />
            <p class="message">{{ message }}</p>
        </div>
    </div>
</template>
<script lang="ts">
import { Vue, Component, Prop } from "vue-property-decorator";

@Component
export default class ToastView extends Vue {
    private type: string = "success";
    @Prop()
    private message!: string;
    private visible: boolean = false;

    success(message: string) {
        this.type = "success";
        this.show(message);
    }

    error(message: string) {
        this.type = "error";
        this.show(message);
    }

    show(message: string) {
        this.message = message;
        this.visible = true;
        setTimeout(() => {
            this.visible = false;
        }, 2000);
    }
}

// Vue.prototype.$toast;
</script>
<style lang="scss" scoped>
// @import "@/theme/_var.scss";
.toast-wrapper {
    position: fixed;
    z-index: 10000;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    .toast-success {
        min-width: 240px;
        max-width: 600px;
        padding: 28px 40px;
        background: rgba(51, 51, 51, 0.8);
        border-radius: 8px;
        line-height: 40px;
        font-size: 28px;
        font-family: PingFang SC-Regular;
        font-weight: normal;
        color: rgba(255, 255, 255, 0.8);
        text-align: center;
        .error-icon {
            display: block;
            margin: 0 auto 16px;
            width: 60px;
            height: 60px;
        }
    }
}
</style>

第二步:main.js文件中引入,手动挂载,作为全局通用组件调用

import Toast from "@/components/Toast/index.vue";
const createElement = () => {
    const div = document.createElement("div");
    document.body.appendChild(div);
    return div;
};
Vue.prototype.$toast = new ToastView().$mount(createElement());

第三步:在需要的文件里直接引用即可

            this.$toast.error("请填写验证码");
            this.$toast.success("提交成功");