1 <template> 2 <transition name="fade"> 3 <div v-show="visible">{{message}}</div> 4 </transition> 5 </template> 6 7 <script> 8 export default { 9 data () { 10 return { 11 visible: false, 12 message: ‘‘ 13 } 14 } 15 } 16 </script> 17 18 <style scoped> 19 div { 20 padding: 5px 20px; 21 color: #fff; 22 background-color: #3596ff; 23 text-align: center; 24 position: fixed; 25 top: 30%; 26 left: 50%; 27 transform: translate(-50%, -50%); 28 } 29 /* vue动画过渡效果设置 */ 30 .fade-enter-active, 31 .fade-leave-active { 32 transition: opacity .5s; 33 } 34 .fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ { 35 opacity: 0; 36 } 37 </style>
import Toasts from ‘./components/Toast‘ const Toast = { install: function (Vue) { // 创建一个Vue的“子类”组件 const ToastConstructor = Vue.extend(Toasts) // 创建一个该子类的实例,并挂载到一个元素上 const instance = new ToastConstructor() // 将这个实例挂载到动态创建的元素上,并将元素添加到全局结构中 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) } } } Vue.use(Toast)
<template> <div> <button @click="onClick">1111</button> </div> </template> <script> export default { name: "App", components: { }, data() { return { }; }, methods:{ onClick(){ // 使用全局 toast this.$toast(‘提示内容‘) } } }; </script> <style lang="less"> </style>
原文:https://www.cnblogs.com/z-j-c/p/12994076.html