<template> <!-- 全局提示框 --> <div v-show="visible" class="dialog-tips dialog-center"> <div>{{message}}</div> </div> </template> <script> export default { data() { return { visible: false, message: "" }; } }; </script> <style lang="scss"> .dialog-tips{ position: fixed; z-index: 100; min-width: 220px; padding: 40px 22px; white-space: nowrap; background-color: #fff; box-shadow: 0px 8px 15px 0 rgba(0, 0, 0, 0.1); text-align: center; .dialog-tips-icon{ width: 54px; height: 54px; @extend %bg-contain; display: inline-block; margin-bottom: 13px; } } .dialog-center { top: 50%; left: 50%; transform: translate(-50%, -50%) } </style>
toast.js
import ToastComponent from './toast.vue' const Toast = {}; // 注冊Toast Toast.install = function (Vue) { // 生成一個Vue的子類 // 同時這個子類也就是組件 const ToastConstructor = Vue.extend(ToastComponent) // 生成一個該子類的實例 const instance = new ToastConstructor(); // 將這個實例掛載在我創建的div上 // 並將此div加入全局掛載點內部 instance.$mount(document.createElement('div')) document.body.appendChild(instance.$el) // 通過Vue的原型注冊一個方法 // 讓所有實例共享這個方法 Vue.prototype.$toast = (msg, duration = 1500) => { instance.message = msg; instance.visible = true; setTimeout(() => { instance.visible = false; }, duration); } } export default Toast
如何使用?
在main.js中
import Vue from 'vue'
import Toast from './toast'
Vue.use(Toast);
在component中
this.$toast("XXXXXXXXX");
