vue.extend () write global components (plug-ins)

extend created is a component constructor, rather than a specific component instance
to create a myToast.vue file:

<template>
    <div class="wrap" v-if="show">
        <div>{{text}}</div>
        <div>{{title}}</div>
    </div>
</template>

<script>
export default {
    data () {
        return {
            title : "你好我是toast"
        }
    }
}
</script>

<style scoped>
    .wrap{
        color:#fff;
        background-color: rgba(0,0,0,0.8);
        padding: 10px;
        position: fixed;
        top:50%;left: 50%;
        border-radius: 10px;
        animation: myfirst 1s;
		-moz-animation: myfirst 1s;	/* Firefox */
		-webkit-animation: myfirst 1s;	/* Safari 和 Chrome */
		-o-animation: myfirst 1s;	/* Opera */
    }
    @keyframes myfirst
		{
		from {opacity: 0;}
		to {opacity: 1;}
	}
    @-moz-keyframes myfirst /* Firefox */
		{
		from {opacity: 0;}
		to {opacity: 1;}
	}
    @@-webkit-keyframes myfirst /* Safari 和 Chrome */
		{
		from {opacity: 0;}
		to {opacity: 1;}
	}
    @-o-keyframes myfirst /* Opera */
		{
		from {opacity: 0;}
		to {opacity: 1;}
	}

</style>

Create a toast.js

import vue from 'vue'
import myToast from './components/myToast'
//使用vue的extend,以vue文件为基础组件,返回一个可以创建vue组件的特殊构造函数
const ToastConstructor =  vue.extend(myToast)
function showToast(text){
    const toastDom = new ToastConstructor({
        el : document.createElement('div'),
        data(){
            return {
                text:text,
                show:true
            }
        }
    })

  //在body中动态创建一个div元素,后面自动会把它替换成整个vue文件内的内容
    document.body.appendChild(toastDom.$el)
    setTimeout(() => {toastDom.show=false},2000) //显示后2秒就消失
}

function registryToast (){
    //把showToast这个方法添加到uve的原型中,可以直接调用,当调用的时候就是执行函数内的内容
    vue.prototype.$toast = showToast
}

export default registryToast

In the entrance js file:

import toastRegistry from './toast.js'
Vue.use(toastRegistry)

Click the button to call a method call this.$toast('哈哈哈哈');results are as follows
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/smlljet/article/details/91863735