vue动态创建组件的方法解析

createApi.js

import Vue from "vue"

// 我的理解,你给我一个组件,我将组件生成的dom 节点挂载到 body 上
// 就是这么简单的一个函数
function create(Component, props) {
    // 借助 Vue 来create  real dom  ,然后添加到body 中
    let instance = new Vue({
        render(h) {
            return h(Component, { props });
        }
    }).$mount();
    const comp = instance.$children[0];
    document.body.appendChild(instance.$el);
    comp.remove = function () {
        // 从body 中移除
        document.body.removeChild(instance.$el);
        instance.$destroy();//将vue 的实例对象销毁
    }
    return comp;
}

export default create;

kk.vue

<template>
  <div v-if="show" class="adv_color">
    hello action
    <el-button @click="closeTap">closeTap</el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      show: false
    };
  },
  methods: {
    start() {
      this.show = true;
    },
    closeTap() {
      this.$emit("i_close");
    }
  }
};
</script>

<style  scoped>
.adv_color {
  color: red;
}
</style>

kk 组件非常简单

一个文字一个按钮

main.js

以上我们可以发现,我们可以动态的创建组件(VNode )动态的销毁!

是不是很牛叉! 以后我们写个全局的弹框啥的,不是很easy!!

猜你喜欢

转载自blog.csdn.net/qq_15009739/article/details/107928668
今日推荐