Vue 全局掛載組件的通用方法:仿elementUI notice

1.文件目錄

|--src
|    |--components
|    |    |--notice
|    |    |    |--Notice.vue #Notice組件
|    |--utils
|    |    |--create.js #掛載方法

2.編寫Notice組件

<template>
    <div class="box" v-if="isShow">
        <h3>{{title}}</h3>
        <p class="box-content">{{message}}</p>
    </div>
</template>

<script>
export default {
    props: {
        title: {
            type: String,
            default: ""
        },
        message: {
            type: String,
            default: ""
        },
        duration: {
            type: Number,
            default: 1000
        }
    },
    data() {
        return {
            isShow: false
        };
    },
    methods: {
        show() {
            this.isShow = true;
            setTimeout(this.hide, this.duration);
        },
        hide() {
            this.isShow = false;
            this.remove();
        }
    }
};
</script>

<style scoped>
.box {
  position: fixed;
  width: 100%;
  top: 16px;
  left: 0;
  text-align: center;
  pointer-events: none;
}
.box-content {
  width: 200px;
  margin: 10px auto;
  font-size: 14px;
  border: blue 3px solid;
  padding: 8px 16px;
  background: #fff;
  border-radius: 3px;
  margin-bottom: 8px;
}
</style>

3.編寫create.js

import Vue from 'vue'

export default function create(Component,props) {
  // 創(chuàng)建實(shí)例
  const vm = new Vue({
    render(h) {
      // h為createElement,返回VNode虛擬Node
      return h(Component,{props})
    }
  }).$mount()

  // 手動(dòng)掛載實(shí)例到body
  document.body.appendChild(vm.$el)

  const comp = vm.$children[0]
  // 銷毀方法
  comp.remove = function() {
    document.body.removeChild(vm.$el)
    vm.$destroy()
  }
  // 返回組件
  return comp
}

4.在main.js中將create掛載到Vue全局

// main.js
import create from "@/utils/create"

Vue.prototype.$create = create

5.調(diào)用

<template>
...
</template>

import Notice from "@/components/notice/Notice"

export default {
  ...
  methods: {
    ...
    handleNotice() {
      const notice = this.$create(Notice,{
        title: '提示',
        message: 'blablablablablabla',
        duration: 2000
      })
    }
  }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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