Vue动态组件

2019-10-07  本文已影响0人  zooeydotmango

Vue的生命周期

export default {
    install(Vue, options) {
        Vue.prototype.$toast = function (message) {
            const constructor = Vue.extend(Toast)
            const toast = new constructor();
            toast.$slots.default = [message]   //默认数组
            toast.$mount();
            document.body.appendChild(toast.$el)
        }
    }
}

如果两行互换则没有效果

当组件中的值是对象

必须用函数返回,因为它是引用类型,如果想要复用就必须每个组件都是新对象

<template>
    <div class="toast">
        <slot></slot>
    </div>
</template>
<script>
    export default {
        name:'zooeyToast',
        props: {
            autoClose:{
                type: Boolean,
                default: true
            },
            autoCloseDelay:{
                type: Number,
                default: 5
            },
            closeButton:{
                type: Object,
                default(){
                    return{
                        text:'关闭',
                        callback:(toast)=>{
                            toast.close()
                        }
                    }
                }
            }
        },
        mounted(){
            if(this.autoClose){
                setTimeout(()=>{
                    this.close()
                }, this.autoCloseDelay*1000)
            }
        },
        methods:{
            close(){
                this.$el.remove()
                this.$destroy()
            }
        }
    }
</script>
上一篇 下一篇

猜你喜欢

热点阅读