如何使用VUE动态的对异步组件进行加载?

需求是 首先通过一个异步的方式获取一个组件名称的列表,然后根据这个列表(字符串数组形式)加载这个列表上的组件,然后循环显示在页面上

先上代码吧:第一种
<template>
  <div class="pageconfig">
    <!-- :gutter="dataArr.layout.gutter" -->

    <el-row :gutter="layout.gutter">
      <el-col :span="itme.span" v-for="(itme,index) in col" :key="index">
        <div class="grid-content bg-purple-dark" >
          <component 
          :is="plugItem" 
          v-for="(plugItem, plugIndex) in plugs" 
          :key="plugIndex"
          ></component>
        </div>
      </el-col>
    </el-row>
  </div>
</template>


<script>
//import '../../uitl/pageConfig.js';
//require
import http from '@/api'
import { PageConfig } from '@/api/url.js'
export default {
  data () {
    return {
      layout: "",
      col: "",
      plugs:[]
    };
  },
  created () {
   
    const _this = this
    http.post(PageConfig, {}, _this).then(res => {
      if (res.code == 0) {
        console.log(res.data)
        _this.layout = res.data.layout
        _this.col = res.data.layout.col
        console.log(_this.layout, "00000----------")
         _this.plugs = []
        res.data.layout.col.forEach(item => {
       //主要是一下这句话
        _this.plugs.push(() => import(`../common/${item.PlugInUnit}`))
      })
       
      }

    }).catch(function (error) {
      _this.$message.error(error);
    });
  },
  computed: {
  },
  methods: {
    
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style scoped lang="scss">
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
  margin-top: 20px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>

主要代码如下:

 _this.plugs.push(() => import(`../common/${item.PlugInUnit}`))

声明变量,然后获取组件信息,进行组件导入:在template体中循环组件

<component 
:is="plugItem" 
v-for="(plugItem, plugIndex) in plugs" 
:key="plugIndex"
>
</component>

第二种

Vue的异步组件实践有两种,第一种是路由懒加载将应用由路由层分为多个chunk,减小单个入口的打包体积。
还有一种就是在Tab页、弹窗等不需要立即展示的都可以使用异步组件进行加载,

<template>
  <div id="pageconfig">
    <component :is="dataAll"></component>
  </div>
</template>

<script>
export default {
  name: 'pageconfig',
  components: {
   table : () => import(`../pageconfig/table`),
    tabs: () => import(`../pageconfig/tabs`),
  },
  data () {
    return {
      plugs: [],
     dataAll: 'table'
    }
  },
}
</script>

首先加载两个动态组件Link1和Link2,通过data中的currentLink来指定动态组件的名称,这样就可以动态的加载组件

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容