組件toast(類似於element-ui的message組件)的實現


實現的toast組件可以通過this.$toast()調用

需要的知識:

vue.extend();

new Vue().$mount(); //如果mount內沒有要掛載的元素vue只會渲染元素而不會加載的界面上

toast.vue的內容

<!--template的內容-->
<template>
    <div>
        <slot>{{message}}</slot>
    </div>
</template>

 

//script的內容
export default {
    name: 'toast',
    data(){
        return {
            duration: 1500, //默認toast消失的時間
            message: '', //toast顯示的內容
        }
    },
    mounted(){
        setTimeout(()=>{
            this.$destroy(true);
            this.$el.parentNode.removeChild(this.$el);
        }, this.duration)
    }
}

toast.js的內容

import Vue from 'vue';
import toast from './toast.vue';

let ToastConstructor = Vue.extend(Toast);

let instance;
let instances = [];

const Toast = function(options) {
    if (Vue.prototype.$isServer) return;
    options = options || {};
    if (typeof options === 'string') {
        options = {
            message: options
        };
    }
    instance = new ToastConstructor({
        data: options
    });
    instance.id = id;
    instance.$slots.default = [instance.message];
    instance.message = null;
    instance.vm = instance.$mount();
    document.body.appendChild(instance.vm.$el);
    
    instance.vm.visible = true;
    instance.dom = instance.vm.$el;
    instances.push(instance);
    return instance.vm;
};

export default Toast;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM