vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > vue自定义组件插入到body中

vue自定义组件插入到body中的实现方式

作者:@红@旗下的小兵

文章介绍了如何在Vue中创建一个自定义的notice提醒组件,并将其插入到body中,该组件通过调用`show`方法显示,调用`remove`方法销毁,主要步骤包括创建组件、使用render函数加载、$mount挂载并插入到body中

vue自定义组件插入到body中

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

实现了两个方法

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

实现思路

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
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文