Vue自定义插件组件

有些时候,像警告框一类的的组件并不需要在每个html中写一遍,只需要在js里直接调用就可以了。

原理就是js在调用的时候动态的加载一个vue component

目录

component/
    ├ vue-alert
        ├ alert.vue
        ├ index.js

创建组件

其实是一个普通的vue component 具体的样式逻辑可以自己定义

alert.vue

<template>
    <div v-show="visible">
        <h2>{{message}}</h2>
    </div>
</template>
export default {
    props: {
        message: String
    },
    data() {
        return {
            visible: false
        }
    },
    methods: {
        show() {
            this.visible = true
        },
        close() {
            this.visible = false
            this.$parent.remove() // 这个地方很重要
        }
    }
}

创建一个插件入口文件

index.js

import alertComponent from 'alert.vue'
export default {
    install(Vue) {
        Vue.prototype.$alert = (opts = {message: '警告'}) => {
            let alertBox = new Vue({
                render(h) {
                    return h(alertComponent, {props: opts})
                },
                methods: {
                    remove() {
                        setTimeout(() => { // 使用timeout可以给组件内的动画预留一些时间
                            this.destroy()
                        }, 300)
                    },
                    destroy() {
                        this.$destroy() //销毁实例
                        document.body.removeChild(this.$el) // 移除html
                    }
                }
            })
            let component = alertBox.$mount() //手动执行声明周期
            document.body.appendChild(component.$el) // 挂载html
            let alertInstance = alertBox.$children[0]
            alertInstance.show() // 这个方法是在alert.vue组件内定义的
        }
    }
}

使用

首先在main.js里import插件 并且加载

import vueAlert from '@/components/vue-alert'

Vue.use(vueAlert)

使用的时候

    this.$alert({
        message: '我是消息提示'
        })