vue动态生成组件

 

完整的代码, 可以复制引用

单个组件引用,引入此文件js。全局使用,注册到vue的main文件Vue.prototype.create = Create

create.js

import Vue from 'vue';
import Toast from './toast'; // 导入Toast组件

// 创建组件实例并挂载到body上的函数
function create(component, props) {
  let temp = null;
  // 根据传入的组件名来决定创建哪个组件
  switch (component) {
    case 'toast':
      temp = Toast;
      break;
    // 如果有其他组件,可以继续扩展
  }

  const vm = new Vue({
    // 使用render函数来创建虚拟DOM,因为webpack中不包含Vue的模板编译器
    render: h => h(temp, {props}) // 使用JSX方式渲染组件并传入props
  }).$mount(); // 生成真实DOM,但此时还没有挂载到页面上

  // 手动将生成的DOM元素挂载到body上
  document.body.appendChild(vm.$el);

  // 获取创建的组件实例
  const comp = vm.$children[0];

  // 给组件实例添加一个remove方法,用于后续手动销毁组件
  comp.remove = () => {
    document.body.removeChild(vm.$el); // 从body中移除DOM元素
    comp.$destroy(); // 销毁Vue组件实例
  };

  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 // 默认显示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;
    width: 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>

调用的地方

// 使用create函数直接显示提示,2.5秒后自动隐藏
this.create('toast', {
  content: '你好啊'
});

// 或者创建组件实例后,手动控制何时隐藏
let aa = Create('toast', {
  second: 2,
  content: '你好啊'
});
setTimeout(() => {
  aa.remove(); // 1秒后手动隐藏提示
}, 1000);

posted on 2020-01-12 19:29  完美前端  阅读(8310)  评论(0)    收藏  举报

导航