vue Toast 弹窗

创建一个message.vue组件

<template>
   <div class="wrap" v-if="showWrap" :class="showContent ?'fadein':'fadeout'">
      <i :class="iconState ?'success':'wrong'"></i>
      {{text}}
    </div>
</template>
<style scoped> .wrap{ position: fixed; left: 50%; top:50%; background: rgba(0,0,0,.6); padding: 10px; border-radius: 5px; transform: translate(-50%,-50%); color:#fff; font-size: 0.1rem; text-align: center; } .fadein { animation: animate_in 0.5s; } .fadeout { animation: animate_out 0.5s; opacity: 0; } @keyframes animate_in { 0% { opacity: 0; } 100%{ opacity: 1; } } @keyframes animate_out { 0% { opacity: 1; } 100%{ opacity: 0; } } .success{ width: 0.2rem; height: 0.2rem; display: block; background: url('../../static/img/sure.png')no-repeat; background-size: 0.2rem 0.2rem; margin: 0.08rem auto; } .wrong{ width: 0.2rem; height: 0.2rem; display: block; background: url('../../static/img/wrong.png')no-repeat; background-size: 0.2rem 0.2rem; margin: 0.08rem auto; } </style>

 

加入 message.js

import vue from 'vue';
import toastComponent from './message.vue'; // 这里就是我们刚刚创建的那个静态组件
const ToastConstructor = vue.extend(toastComponent); // 返回一个 扩展实例构造器
var Test = true;
// 定义弹出组件的函数 接收2个参数, 要显示的文本 和 显示时间
function showToast (text, iconState, duration = 2000) {
    if (Test === false) {
        return;
    }
    const toastDom = new ToastConstructor({
        el: document.createElement('div'),
        data () {
            return {
                text: text,
                showWrap: true, // 是否显示组件
                showContent: true, // 作用:在隐藏组件之前,显示隐藏动画
                iconState: iconState
            };
        }
    });
    document.body.appendChild(toastDom.$el);
    Test = false;
    // 过了 duration 时间后隐藏整个组件
    setTimeout(() => {
        toastDom.showWrap = false;
        Test = true;
    }, duration);
}

// 注册为全局组件的函数
function registryToast () {
    // 将组件注册到 vue 的 原型链里去,
    // 这样就可以在所有 vue 的实例里面使用 this.$message()
    vue.prototype.$message = showToast;
}

export default registryToast;

  

引入到index.js 或者引入到main.js

import Vue from 'vue';
import toastRegistry from '@/components/message/message';
Vue.use(toastRegistry);
new Vue({
    el: '#app',
    template: '<App />',
    components: {
        App
    }
});