首先在components新建組件文件夾
隨后在toast.vue中寫入彈框樣式
<template> <transition name="demo"> <div class="toast" v-show="theToast"> {{msg}} </div> </transition> </template> <script> export default { data() { return { theToast: false, msg: "" }; } }; </script> <style lang="less" scoped> .toast { position: fixed; top: 40%; left: 50%; margin-left: -15vw; padding: 2vw; width: 30vw; font-size: 4vw; color: #fff; text-align: center; background-color: rgba(0, 0, 0, 0.8); border-radius: 5vw; z-index: 999; } .demo-enter-active, .demo-leave-active { transition: 0.3s ease-out; } .demo-enter { opacity: 0; transform: scale(1.2); } .demo-leave-to { opacity: 0; transform: scale(0.8); } </style>
隨后在index.js中寫下核心js部分
import ToastComponent from './toast.vue'// 引入先前寫好的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的原型注冊一個方法 // 讓所有實例共享這個方法
// 其中的duration是持續時間 Vue.prototype.$toast = (msg, duration = 1250) => { instance.msg = msg; instance.theToast = true; setTimeout(() => { instance.theToast = false; }, duration); } } export default Toast
隨后在main.js之中注冊
之后就可以直接使用了
使用this.$toast調用
實現效果: