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) {
  // 创建实例
  const vm = new Vue({
    render(h) {
      // h为createElement,返回VNode虚拟Node
      return h(Component,{props})
    }
  }).$mount()

  // 手动挂载实例到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.调用

<template>
...
</template>

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

export default {
  ...
  methods: {
    ...
    handleNotice() {
      const notice = this.$create(Notice,{
        title: '提示',
        message: 'blablablablablabla',
        duration: 2000
      })
    }
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容