Vue 使用 函數調用組件 的方法

之前寫過一篇 react 方法組件構造 Loading 的使用

現在這篇就是 Vue 版本的 方法調用組件了

組件還是 vue 組件,這個和之前是一樣的

Toast/Toast.vue

<template>
  <div class="toast" v-if="show">
    <div class="mask" v-if="showMask"></div>
    <div class="message">{{ message }}</div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      showMask: false,
      message: '',
      t: null,
      show: false
    }
  },
  methods: {
    showToast({ message = '', showMask = false, length = 3000 }) {
      this.message = message
      this.showMask = showMask
      this.show = true
      this.t && clearTimeout(this.t)
      this.t = setTimeout(() => {
        this.show = false
      }, length)
    },
    hideToast() {
      this.show = false
    },
    destory() {
      this.$destroy()
    }
  }
}
</script>
<style lang="less" scoped>
.toast {
  .mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.1);
    z-index: 100;
  }
  .message {
    color: white;
    background-color: rgba(0, 0, 0, 0.6);
    border-radius: 5px;
    padding: 10px;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -60%);
    z-index: 100;
  }
}
</style>

Toast/index.js

import Vue from 'vue'
import Toast from './Toast.vue'

let toastVue

function createToast() {
  // 這裏使用了 VUE 來構建一個 vnode
  // 值得注意的是, $mount() 函數沒有填寫任何的 dom 節點
  // 這樣就變成了一個 未掛載 的 vnode 
  const vnode = new Vue({
    render: h => h(Toast)
  }).$mount()
  // 手動 將 生成的對應 dom 插進 body 裏面
  document.body.appendChild(vnode.$el)
  // 返回當前實例  的 vue 對象
  // 沒錯,就是 $children[0]
  return vnode.$children[0]
}

export function showToast(args, callback) {
  // 爲了讓當前的實例 只有一個,防止佔用太多內存
  if (!toastVue) {
    toastVue = createToast()
  }
  toastVue.showToast(args)
  callback && callback()
  return toastVue
}

export function hideToast() {
  if (!toastVue) return
  toastVue.hideToast()
  return toastVue
}

export function destoryToast() {
  if (!toastVue) return
  toastVue.destory()
}

export default showToast

關於 調用:

import ShowToast from '@/components/Toast'


created() {
  // 這樣就能對 當前的 Toast 組件進行調用了
  ShowToast({
     message: 'hhhhh',
     showMask: true
  })
}

頁面效果:

 

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