1. 程式人生 > 其它 >封裝成外掛---Toast

封裝成外掛---Toast

將Toast元件封裝成外掛形式

需求:經常會有提示框,多個頁面使用,但是提示框的大小、icon圖示等會變化。

思路:多個頁面使用,可以封裝成全域性元件。但是需要多次引人標籤,有點繁瑣。

一、建立Toast元件

<template>
  <div class="tip" :style="{width: tipObj.width+'px',height:tipObj.height+'px',padding:tipObj.padding+'px',paddingTop:tipObj.paddingTop+'px '}" v-show="isShowTip">
     <span class="iconfont" :class="tipObj.icon" :style="{fontSize:tipObj.iconfontSize+'px'}"></span>
      <p class="tip_text" v-html="tipObj.text" :style="{fontSize:tipObj.fontSize+'px'}">
      </p>
  </div>
</template>
<script>
  export default {
    name: "Tip",
    data(){
      return{
        isShowTip:false,
        tipObj:{
          width:150, 
          height:50,
          padding:9,
          paddingTop:9,
          fontSize:14,
          iconfontSize:12,
          icon:'',//小icon圖示樣式
          text:'',//顯示的內容
          time:2000 //預設顯示時間
        }
      }
    },
    methods:{
      showToast(tipObj) {
        this.isShowTip = true;
        this.tipObj=Object.assign(this.tipObj, tipObj);
        const timeId = setTimeout(() => {
          this.isShowTip = false;
          clearTimeout(timeId);
        }, this.tipObj.time);
      },
    }
  }
</script>

二、元件使用形式

<tip  ref="tip"></tip>
this.$refs.tip.showToast({//其他值不傳,是按預設值
  text: 'HAHAHAHAH',
  time:5000
});

三、封裝成外掛的形式

  • 在元件中建一個js檔案(toast/index.js)
import Toast from './Toast'
const obj={};
obj.install=function (Vue) {
  //1、建立元件構造器
  const toastContrustor=Vue.extend(Toast);
  //2、new的方式,根據元件構造器,可以創建出來一個元件物件
  const toast =new toastContrustor();
  //3、將元件物件,收手動掛載到某一個元素上去
  toast.$mount(document.createElement('div'));
  // 4、toast.$el對應的就是div
  document.body.appendChild(toast.$el);
  Vue.prototype.$toast=toast
}
export default obj
  • 安裝元件
import toast from 'components/common/toast/index'
// 安裝toast外掛
Vue.use(toast);//使用use,就會去執行tip的install函式
  • 外掛的使用
this.$toast.showToast({
  text: 'HAHAHAHAH',
  time:5000
})

作者:黃哈哈。

原文連結:https://www.cnblogs.com/jiajia-hjj/p/15864429.html

本部落格大多為學習筆記或讀書筆記,本文如對您有幫助,還請多推薦下此文,如有錯誤歡迎指正。