手动挂载组件-demo

  • 官方文档:https://cn.vuejs.org/v2/api/#vm-mount
  • 仿写 elementUIthis.$message
  1. MyNotice/MyNotice.vue



  1. MyNotice/index.js
import Vue from 'vue'
import MyNotice from './MyNotice.vue'

let noticInstance = null,
    NoticeConstructor = Vue.extend(MyNotice),
    init = () => {
        noticInstance = new NoticeConstructor()
        noticInstance.$mount()
        document.body.appendChild(noticInstance.$el)
    },
    caller = (opt) => {
        if (!noticInstance) {
            init()
        }
        noticInstance.add(opt)
    }

export default {
    // 返回 install 函数 用于 Vue.use 注册
    install(vue) {
        vue.prototype.$notice = caller
    },
}
  1. main.js
import MyNotice from '@/components/MyNotice/index.js'

Vue.use(MyNotice)
  1. 调用
 myNotice() {
    this.$notice({
        type: "success",
        content: "成功信息提示",
        duration: 2000,
    })
 }

你可能感兴趣的:(手动挂载组件-demo)