一:在項目中創建一個plugins\ToastMessage\index.vue文件
<template> <div class="wrap" v-if="showWrap" :class="showContent ?'fadein':'fadeout'">{{text}}</div> </template> <style scoped> .wrap{ position: fixed; left: 50%; top:50%; background: rgba(0,0,0,.35); padding: 10px; border-radius: 5px; transform: translate(-50%,-50%); color:#fff; } .fadein { animation: animate_in 0.25s; } .fadeout { animation: animate_out 0.25s; opacity: 0; } @keyframes animate_in { 0% { opacity: 0; } 100%{ opacity: 1; } } @keyframes animate_out { 0% { opacity: 1; } 100%{ opacity: 0; } } </style>
二:在該目錄下創建Index.js文件
import vue from 'vue' // 這里就是我們剛剛創建的那個靜態組件 import toastComponent from './index.vue' // 返回一個 擴展實例構造器, 關於 vue.extend 有不懂的同學,可以去查看以下官方文檔 https://cn.vuejs.org/v2/api/#Vue-extend const ToastConstructor = vue.extend(toastComponent) // 定義彈出組件的函數 接收2個參數, 要顯示的文本 和 顯示時間 function showToast(text, duration = 2000) { // 實例化一個 toast.vue const toastDom = new ToastConstructor({ el: document.createElement('div'), data() { return { text: text, showWrap: true, showContent: true } } }) // 把 實例化的 toast.vue 添加到 body 里 document.body.appendChild(toastDom.$el) // 提前 250ms 執行淡出動畫(因為我們再css里面設置的隱藏動畫持續是250ms) setTimeout(() => { toastDom.showContent = false }, duration - 250) // 過了 duration 時間后隱藏整個組件 setTimeout(() => { toastDom.showWrap = false }, duration) } // 注冊為全局組件的函數 export function registryToast() { // 將組件注冊到 vue 的 原型鏈里去, // 這樣就可以在所有 vue 的實例里面使用 this.$toast() vue.prototype.$toast = showToast } export default showToast
三:main.js進行引用
import { registryToast } from './plugins/ToastMessage' // message 提示消息插件 Vue.use(registryToast)
四:vue文件中使用
this.$toast('消息');
五:js文件中使用
import showToast from '../plugins/ToastMessage'; showToast('消息');