Vue中封裝toast插件


一:在項目中創建一個plugins\ToastMessage\index.vue文件

<template>
  <div class="wrap" v-if="showWrap" :class="showContent ?'fadein':'fadeout'">{{text}}</div>
</template>

<style scoped>
  .wrap{
    position: fixed;
    left: 50%;
    top:50%;
    background: rgba(0,0,0,.35);
    padding: 10px;
    border-radius: 5px;
    transform: translate(-50%,-50%);
    color:#fff;
  }
  .fadein {
    animation: animate_in 0.25s;
  }
  .fadeout {
    animation: animate_out 0.25s;
    opacity: 0;
  }
  @keyframes animate_in {
    0% {
      opacity: 0;
    }
    100%{
      opacity: 1;
    }
  }
  @keyframes animate_out {
    0% {
      opacity: 1;
    }
    100%{
      opacity: 0;
    }
  }
</style>

二:在該目錄下創建Index.js文件

import vue from 'vue'

// 這里就是我們剛剛創建的那個靜態組件
import toastComponent from './index.vue'

// 返回一個 擴展實例構造器, 關於 vue.extend 有不懂的同學,可以去查看以下官方文檔 https://cn.vuejs.org/v2/api/#Vue-extend
const ToastConstructor = vue.extend(toastComponent)

// 定義彈出組件的函數 接收2個參數, 要顯示的文本 和 顯示時間
function showToast(text, duration = 2000) {

  // 實例化一個 toast.vue
  const toastDom = new ToastConstructor({
    el: document.createElement('div'),
    data() {
      return {
        text: text,
        showWrap: true,
        showContent: true
      }
    }
  })

  // 把 實例化的 toast.vue 添加到 body 里
  document.body.appendChild(toastDom.$el)

  // 提前 250ms 執行淡出動畫(因為我們再css里面設置的隱藏動畫持續是250ms)
  setTimeout(() => { toastDom.showContent = false }, duration - 250)
  // 過了 duration 時間后隱藏整個組件
  setTimeout(() => { toastDom.showWrap = false }, duration)
}

// 注冊為全局組件的函數
export function registryToast() {
  // 將組件注冊到 vue 的 原型鏈里去,
  // 這樣就可以在所有 vue 的實例里面使用 this.$toast()
  vue.prototype.$toast = showToast
}

export default showToast

三:main.js進行引用

import { registryToast } from './plugins/ToastMessage' // message 提示消息插件
Vue.use(registryToast)

四:vue文件中使用

this.$toast('消息');

五:js文件中使用

import showToast from '../plugins/ToastMessage';
showToast('消息');

 


免責聲明!

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



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