vue |封装全局提醒组件

参考文章https://segmentfault.com/a/1190000019487630

组件特点

  • 自定义文本
  • 自定义提醒图标
  • 自定义过渡时间
  • 自定义位置
  • 显示隐藏过渡

20201106-154349.gif

目录结构

image-20201106154603646.png

/toast.vue

<template>
  <!-- 一个显示隐藏过渡 --> 
  <transition name="fade">
    <div class="toastbox" v-if="show" :style="{top:top,left:left}">
      <div class="iconbox">
          <i :class="icon"></i>
      </div>
      <div class="textbox">
          {{text}}
      </div>
    </div>
  </transition>
</template>

<script>
export default {
};
</script>

<style>
.toastbox{
    width: 11em;
    height: 11em;
    position: absolute;
    margin-left: -5.5em;//水平居中:left:50%,margin-left:'自身元素宽度的一半'
    border-radius: .4em;
    background: rgba(0, 0, 0, 0.8);
    position: absolute;
    color: white;
}
.iconbox{
    display: block;
    margin: 1em auto .8em;
    text-align: center;
    font-size: 2.2em;
}
.textbox{
    text-align: center;
}


.fade-enter-active {
  transition: all .5s ease;
}
.fade-leave-active {
  transition: all .3s ease;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}
</style>

/index.js

import vue from 'vue'
import toastComponent from './toast.vue'
 
// 组件构造器,构造出一个vue组件实例
const ToastConstructor = vue.extend(toastComponent)
 
function showToast ({ text,duration = 3000,icon='el-icon-check',top='30%',left='50%' }) {
 const toastDom = new ToastConstructor({
  el: document.createElement('div'),
  data () {
   return {
    show: true,// 是否显示
    text: text,// 文本内容
    icon: icon,// 图标
    top:top,// 离上方的距离
    left:left,// 离左边的距离
   }
  }
 })
 // 添加节点
 document.body.appendChild(toastDom.$el)
 // 过渡时间:规定多久后隐藏组件
 setTimeout(() => {
  toastDom.show = false
 }, duration)
}

// 全局注册
function registryToast () {
 vue.prototype.$toast = showToast
}
 
export default registryToast

全局注册

/mian.js

import toastRegistry from './toast/index'
Vue.use(toastRegistry)

调用

this.$toast({
	text: '群组数据保存成功!',
    left:'75%',
    top:'40%'
})
posted @ 2020-11-06 16:00  sanhuamao  阅读(914)  评论(0编辑  收藏  举报