vite+vue2使用vue-grid-layout布局结合动态组件component

具体用法以及属性这里不介绍,请看官方文档

https://jbaysolutions.github.io/vue-grid-layout/zh/guide/properties.html

值得注意的是vite+vue中使用动态组件的写法:
使用 import.meta.glob 函数从文件系统导入多个模块:
const modules = import.meta.glob('../../components/*/index.vue');
通过 modules 对象的 key 值来访问相应的模块
component: modules['../../components/1-energy-monitor/index.vue‘],

遇到的坑:最开始grid-layout组件绑定data中的值,动态组件一直不显示,后来我发现grid-layout会修改绑定的布局数组的值,但是修改的值中component动态组件字段会丢失,所以只能使用computed,然后set时合并一下布局数组的值,具体代码看下方

<template>
  <div class="home">
      <grid-layout
        :layout.sync="gridLayout"
        :col-num="12"
        :row-height="30"
        :is-draggable="true"
        :is-resizable="true"
        :responsive="true"
        :vertical-compact="true"
        :use-css-transforms="true">
        <grid-item
          v-for="item in gridLayout"
          :static="item.static"
          :x="item.x"
          :y="item.y"
          :w="item.w"
          :h="item.h"
          :i="item.i">
          <component :is="item.component"></component>
        </grid-item>
      </grid-layout>
  </div>
</template>

<script>
const modules = import.meta.glob('../../components/*/index.vue');
export default {
  data() {
    return {
      layout: [
        {
          x: 0,
          y: 0,
          w: 6,
          h: 8,
          i: '0',
          static: false,
          component: modules[`../../components/1-energy-monitor/index.vue`],
        },
        {
          x: 6,
          y: 0,
          w: 6,
          h: 8,
          i: '1',
          static: false,
          component:
            modules[`../../components/2-all-electricity-condition/index.vue`],
        },
      ],
    };
  },
  computed: {
    gridLayout: {
      get() {
        return this.layout;
      },
      set(v) {
        // 不能直接this.layout = v,需要合并,因为component属性会丢失
        this.layout.forEach((item, index) => {
          v[index] = {
            ...item,
            ...v[index],
          };
        });
        this.layout = v;
      },
    },
  },
};
</script>
<style scoped lang="scss">
.home {
  height: 100%;
}
</style>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值