以notice提醒组件为例,调用组件,如下,

实现了两个方法:

show方法时显示组件

remove方法销毁组件

// 加载组件
let noticeCom = vm.$create({
    title: '提醒标题', 
    content: '提醒内容',
    duration: 2000 // 组件的显示时长
}).show()
// 销毁
noticeCom.remove()

实现思路:

(1)首先创建组件

(2)使用render函数加载组件

(3)$mount挂载组件,把组件渲染为真实dom

(4)把dom插入到body中去

Notice.vue组件:

<!--Notice.vue组件-->
<template>
  <div v-if="isShow" class="notices">
     <div>{{title}}</div><div>{{contents}}</div>
  </div>
</template>
<script>
export default {
    props: {title: String, contents: String, duration: Number},
    data() {return {isShow: false}},
    methods: {
        show() { // show 方法控制组件的显示
            this.isShow = true
            let timer = setTimeout(() => {
                this.isShow = false
                clearTimeout(timer)
            }, this.duration)
        }
    }
}
</script>

在main.js中,把渲染Notice组件的方法挂载到vue实例上:

// main.js 把notice组件渲染挂载到vue实例上
import notice from "@/components/notice.js"
Vue.prototype.$create = notice

notice.js:

// notice.js 加载组件的主文件
import Vue from 'vue'
export default function create(component, props) {
    let vm = new Vue({
        // 使用render函数渲染组件
        render(h) {
            return h(component,{props})
        }
    }).$mount()
    document.body.appendChild(vm.$el) // vm.$el 是Notice组件挂载的根节点<div class="notices">··· ···</div>
    const noticeComponent = vm.$children[0]
    // 组件挂载销毁实例的方法(实际就是删除dom)
    noticeComponent.removeNotice = function () {
        document.body.remove(vm.$el)
    }
    return noticeComponent
}

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐