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%'
})


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM