vue封裝一個toast插件

本文學(xué)習(xí)來自于coderwhy大神的一個視頻項(xiàng)目內(nèi)。
先創(chuàng)建這個插件的文件夾,里邊一個index.js和一個Toast.vue文件。


image.png

創(chuàng)建這個Toast
其實(shí)就是一個組件,只是展示方式不同。需要的時候再展示它
實(shí)現(xiàn)功能:
主要是實(shí)現(xiàn)了提示用戶的功能,用戶可以傳入不同的展示內(nèi)容,并可以設(shè)置在幾秒后關(guān)閉。

<template>
    <div class="toast" v-show="isShow">
            {{message}}
    </div>
</template>

<script>
export default {
    data(){
        return{
            isShow:false,
            message:'加載中。。。'
        }
    },
    methods:{
        show(message,duration=2000){
            this.isShow = true;
            this.message = message
            setTimeout(()=>{
                this.isShow = false
                this.message = ''
            },duration)
        }
    }
}
</script>

<style>
    .toast {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 8px 10px;
  color: aliceblue;

  z-index: 9999;

  background-color: rgba(0, 0, 0, 0.75);
}

</style>

index.js內(nèi)寫核心內(nèi)容:

//引用組件 用于Vue.use來安裝
import Toast from './Toast' //引入插件組件
const obj  = {}
obj.install = function(Vue){ //install通過Vue.use安裝
   // 1、必須創(chuàng)建組件構(gòu)造器
   const toastContrustor = Vue.extend(Toast)
   //2、new的方式,根據(jù)組件構(gòu)造器,可以創(chuàng)建出來一個組件對象
   const toast = new toastContrustor()
   //3、將組件對象toast,手動掛載到某一個元素div上
   toast.$mount(document.createElement('div'))
   //4、toast.$el對應(yīng)的就是div
   document.body.appendChild(toast.$el)
   //5、將此插件添加到原型中
   Vue.prototype.$toast = toast
}
export default obj


main.js下引入這個js,并進(jìn)行安裝
它就會去 toast 的index.js文件里執(zhí)行 install函數(shù);
注意:use 括號中的toast 相當(dāng)于是個形參 它代表著 js 文件中的 obj 這個對象

import toast from './common/Toast/index.js'
Vue.use(toast) 

最后,其他所有頁面都能使用了

  this.$toast.show('加載一中',5000)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容