通过Vue.extend + $mount方法来构造一个带动画的可调用的全局组件,效果如下

vue自定义一个全局消息弹窗组件

步骤如下

  1. 先在components/目录下创建一个tips的文件夹
  2. 再新建index.vuetips.js的文件
  3. 分别填入以下内容,并且修改main.js文件内容和public目录下index.html的内容
index.vue
<template>
    <div class="msgbox fadein">
        <span>{{ msg }}</span>
    </div>
</template>

<script>
export default {
    name: "tipsCom",
    data() {
        return {};
    },

    props: {
        msg: {
            type: String,
            default: "",
        }
    },
};
</script>

<style scoped>
.msgbox {
    min-height: 40px;
    background: rgba(1, 1, 1, 0.7);
    color: rgb(221, 215, 215);
    border-radius: 8px;
    text-align: center;
    display: flex;
    flex-direction: column;
    justify-content: center;
        margin-top: 1em;
}
.msgbox span {
    word-break: break-all;
    margin: 1em;
}
</style>
tips.js
import msgTip from "./index.vue";
import Vue from "vue";

const messageTips = Vue.extend(msgTip);
const msgArea = document.getElementById("msg-area")

export function tips(option) {
    let instance = new messageTips().$mount();
    Object.assign(instance, option);
    msgArea.appendChild(instance.$el);
    setTimeout(() => {
        instance.$el.classList.add("fadeout")
    }, 2800);
    setTimeout(() => {
        if (instance.$el) instance.$el.remove();
    }, 3000);
}

["success", "info", "error"].forEach((type) => {
    tips[type] = (options) => {
        options = {
            msg: options,
        };
        return tips(options);
    };
});
main.js
import { tips } from '@/components/tips/tips'
Vue.prototype.$tips = tips;  // 在这里挂载到全局
public/index.html
<!-- 新增一个消息容器 -->
<body>
    <div id="msg-area"></div>
    <div id="app"></div>
</body>
文章目录
文章目录