VUE:從toast組件到toast插件(二)

在上一篇文章當中,我們簡述了在vue的項目中toast組件的使用,可以說是非常麻煩,現在我就來簡述一下如何搞一個toast插件。

其實比較理想的使用方式是在項目中隨心所欲的使用,如:this.$toast.show("展示的內容", 多長時間後關閉)。

一、改造Toast.vue

//components/common/toast/Toast.vue

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

<script>
export default {
  name: "Toast",
  data() {
    return {
      isShow: false,
      content: "",
      times: null
    };
  },
  methods: {
    show(text = "操作成功", duraction = 3) {
      this.content = text;
      this.isShow = true;
      if (this.times) clearTimeout(this.times);
      this.times = setTimeout(() => {
        this.content = "";
        this.isShow = false;
      }, duraction * 1000);
    }
  }
};
</script>

<style lang="scss" scoped>
.toast-box {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 99999;

  max-width: 80%;
  height: auto;
  padding: 2rem 2rem;
  box-sizing: border-box;
  border-radius: 0.5rem;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
}
</style>

上面是在Toast組件中寫了一個show方法,自主控制顯示和隱藏;

二、關鍵的一步,在同級目錄下創建一個插件入口文件index.js

//components/common/toast/index.js

import Toast from './Toast.vue';

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;

每一步的註釋我都寫上去了,不要問爲什麼,問了就是不知道;

三、在項目入口文件main.js引入並使用

// main.js

import Vue from 'vue';
import toast from 'common/toast';

Vue.use(toast);

四、接下來,就是隨心所欲的使用了

// views/home/Home.vue

<template>
    <div class="home">
        <button @click.stop = "showToast" >點擊顯示toast</button>
    </div>
</template>

<script>
export default {
    name: "Home",
    components:{
        Toast,
    },
    methods:{
        showToast(){
            this.$toast.show("這是一個toast", 3)
        }
    }
}
</script>

基本上四部就可以搞定了,如果有啥疑問,歡迎交流,最後感謝coderwhy老師!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章