vue自定义组件 -弹窗

779 阅读1分钟

弹窗是独立存在的 脱离vue 挂在body下
//服务类的方式
this.$create(Notice,{ title:'title', message:'提示信息', duration:1000 }).show()

[utils/create.js]
import Vue from 'vue'
export default function(Comp,props){
//组件实例化
//方法1 用new Vue comp当做根组件
//new Vue({
//   render:(h)=>h(Comp)
//})
//方法2 继承Comp 得到组件构造函数
const Ctor = Vue.extend(Comp)
const comp = new Ctor({
    propsData: props
}) //得到组件实例

//挂在到body
comp.$mount() //执行空挂在获取dom 获取$el
document.body.appendChild(comp.$el)

//淘汰方法
comp.remove = () => {
    document.body.removeChild(comp.$el)
    comp.$distory()
}

//返回实例
    return comp
}
[Notice]
<template>
    <div v-if="isShow">
        <h3>{{title}}</h3>
        <p>{{message}}</p>
    </div>
</template>
<script>
    export default{
        props:{
            title:String,
            message:String,
            duration:Number
        },
        data(){
            return{
                isShow:false
            }
        },
        methods{
            show(){
                this.isShow=true
                setTimeout(this.hide,this.duration)
            },
            hide(){
                this.isShow = false,
                this.remove()
            }
            
        }
    }
</script>

[index]
import Notice from './component/Notice.vue'
import create from './utils/create'

Vue.prototype.$notice = function(opts){
    const comp = create(Notice,opts)
    comp.show()
    return comp
}

methods:{
    onLogin(){
        this.$create(Notice,{})
        this.$notice({
            title:'',
            message:''
        })
    }
}