創建一個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 } });