• vue动态注册组件


    vue的架构思想,其实就是想按组件化开发,提升前端的模块复用性,因此在开发过程中,组件的嵌套是很正常的需求。

    例如以下需求:

    在Index.vue页面想调用组件A,A的页面有两种样式,分别为B,和C,想在Index.vue调用两个A组件,并且A组件包含有B和C样式。

    那么在开发的时候,我习惯把B和C的样式和事件分别封装为B组件和C组件,如下图:

    这个需求要求我们在Index.vue页面传递参数给A组件,然后A组件通过参数决定是调用B组件还是C组件,代码如下

    Index.vue:

    <template>
      <div class="Index">
       <div class="box"><A comChilds="C"></A></div>
        <div class="box"><A comChilds="B"></A></div>
      </div>
    </template>
    
    <script>
    import A from "@/components/A";
    export default {
      name: "Index",
      data() {
        return {
         
        };
      },
      components: {
        A: A
      }
    };
    </script>
    
    <!-- Add "scoped" attribute to limit CSS to this component only -->
    <style scoped>
    .Index{ 800px;border:solid 1px #000;display: flex;text-align: center}
    
    .box{ 300px;margin:10px 25px }
    </style>
    

      组件A的:

    <template>
      <div>
        <div>父类组件A</div>
        <component :is="apps"></component>
      </div>
    </template>
    <script>
    import Vue from "vue";
    export default {
      name: "A",
      data() {
        return {
          Child: this.comChilds,
          apps: {}
        };
      },
      props: {
        comChilds: {
          type: String
        }
      },
      beforeMount() {
      
       this.apps=() => import('./common/' + this.Child + '.vue')
       
      }
    };
    </script>
    <style scoped>
    </style>
    

      组件B:

    <template>
        <div>我是A组件下的子组件B</div>
    </template>
    <script>
    export default {
        
    }
    </script>
    <style scoped>
    
    </style>
    

      组件C:

    <template>
        <div>我是A组件下的子组件C</div>
    </template>
    <script>
    export default {
        
    }
    </script>
    <style scoped>
    
    </style>
    

      

     补充说明:

    A组件中的:this.apps=() => import('./common/' + this.Child + '.vue')作用为:动态加载,可以使用
    this.apps=resolve => require.ensure([], () => resolve(require('./common/' + this.Child + '.vue')));代替
    也可以使用
    this.apps=require("./common/"+this.Child+".vue").default代替
    生命周期(钩子):beforeMount也可以使用created代替,可以查看VUE的API生命周期
    
    
     
     
  • 相关阅读:
    升级:Logical Upgrade升级MySQL5.6.26
    基于GTID恢复误篡改数据
    mysql迁移:ibd表空间迁移库表
    mysql迁移:xtrabackup迁移mysql5.7.32
    Pycharm最新激活码2019
    转载:Prometheus+Grafana搭建HBase监控仪表盘
    总结《Elasticsearch源码解析和优化实战》第一讲
    yarn resourcemanager调优
    presto安装和集成kerberos的hive
    转载:shell expect实战实例
  • 原文地址:https://www.cnblogs.com/PiaoYu/p/10759554.html
Copyright © 2020-2023  润新知