zoukankan      html  css  js  c++  java
  • vue动态生成组件

    单个组件引用,引入此文件js。全局使用,注册到vue的main文件Vue.prototype.create = Create
    create.js
    import Vue from 'vue';
    import Toast from './toast'; 组件名


    function create(component, props) {

    let temp = null;
    switch (component) {
    case 'toast':
    temp = Toast;
    break;
    }
    const vm = new Vue({
    // 为什么不使用 template 要使用render 因为现在是webpack里面没有编译器 只能使用render
    render: h => h (temp, {props}) // render 生成虚拟dom {props: props}
    }).$mount(); // $mount 生成真实dom, 挂载dom 挂载在哪里, 不传参的时候只生成不挂载,需要手动挂载

    // 手动获取挂载dom元素
    document.body.appendChild(vm.$el);

    // 回收组件
    const comp = vm.$children[0];
    comp.remove = () => {
    document.body.removeChild(vm.$el); // 删除元素
    comp.$destroy(); // 销毁组件
    };
    return comp;
    }

    export default create;

    toast组件
    <template>
    <section class="loading-bg" v-if="show">
    <section class="toast">
    {{content}}
    </section>
    </section>
    </template>

    <script>
    export default {
    name: 'toast',
    props: {
    second: {
    type: Number,
    default: 2.5
    },
    content: {
    type: String,
    default: ''
    }
    },
    data() {
    return {
    show: true
    }
    },
    created() {
    setTimeout(() => {
    this.show = false;
    }, this.second * 1000);
    }
    }
    </script>

    <style scoped>
    .loading-bg{
    position: fixed;
    z-index: 99999;
    top: 0;
    left: 0;
    100%;
    height: 100%;
    background: rgba(0,0,0,0);
    }
    .toast{
    position: absolute;
    top: 0;
    left: 50%;
    bottom: 0;
    margin: auto 0;
    padding: 0 6px;
    height: 30px;
    line-height: 30px;
    font-size: 14px;
    transform: translateX(-50%);
    border-radius: 4px;
    white-space: nowrap;
    background: rgba(0,0,0,.7);
    color: #fff;
    }
    </style>


    调用的地方
    this.create('toast', {
    content: '你好啊'
    })

    或者
    let aa = Create('toast', {
    second: 2,
    content: '你好啊'
    })
    setTimeout(() => {
    aa.remove();
    }, 1000)
  • 相关阅读:
    CSS教程:div垂直居中的N种方法
    .NET中Flags枚举的使用
    C# 两种方法实现HTTP协议迷你服务器
    百度面试题:求绝对值最小的数
    单点登录
    三范式
    hibernate cascade
    debugview trace 调试
    面向模式的软件体系结构
    待研究
  • 原文地址:https://www.cnblogs.com/zhaofeis/p/12184409.html
Copyright © 2011-2022 走看看