基于vue和flex实现页面可配置组件顺序

需求

已有实现:页面存在A、B、C三个组件按照ABC顺序展示,不支持后台配置顺序 期望改成:组件的顺序支持配置,比如后台配置B,C,A,那么页面的展示顺序为B、C、A

实现

方案实现,需要考虑不能影响到组件原来的逻辑,还需要考虑可扩展性,比如后续迭代新增一个组件D,可以方便地接入本方案。

实现的核心就是利用flex布局的order设置组件的顺序。

假设产品经理/运营人员配置的order是B,C,A,我们先把这串字符串改为配置映射

js 复制代码
const getOrderConfig = (order) => {
  const orderConfig = {}
  order.split(',').forEach((orderKey, index) => {
    orderConfig[orderKey] = index + 1
  })
  return orderConfig
}

实现一个flex布局的包裹组件OrderWrapper,结合使用vue的具名插槽,插槽的name就是上述配置映射的orderKey

vue 复制代码
<script setup name="OrderWrapper">
import { defineProps, computed } from 'vue'

const props = defineProps({
  orderConfig: {
    type: Object,
    default: () => ({}),
  }
})

const orderKeys = computed(() => Object.keys(props.orderConfig))
</script>

<template>
  <div style="display:flex;flex-direction:column;">
    <div
      v-for="orderKey in orderKeys"
      :key="orderKey"
      :style="{ order: orderConfig[orderKey] }"
    >
      <slot :name="orderKey" />
    </div>
  </div>
</template>

OrderWrapper组件的使用如下:

vue 复制代码
<Comp :order-config="orderConfig">
  <template v-slot:A>
    <A />
  </template>
  <template v-slot:B>
    <B />
  </template>
  <template v-slot:C>
    <C />
  </template>
</Comp>

如果想自己改改代码,试试效果,可以点下面这个playground链接

示例代码的playground演示

相关推荐
幼儿园技术家4 分钟前
实现 GEO 监控:从多引擎探测到优化闭环
前端·后端
甲维斯4 分钟前
GLM5.2+ZCode复刻坦克大战,自测50万帧!
前端·ai编程·游戏开发
Csvn1 小时前
useRef 的 5 个冷门但救命的高级用法
前端
小小小小宇1 小时前
Harness Engineering 与 AI 联动
前端
mqcode1 小时前
你项目里的 axios,封对了吗?从裸用到生产级的四步进化
vue.js·axios
鱼人1 小时前
HTML5 页面性能优化大全
前端
ping某1 小时前
专栏-null 和 undefined 到底是什么?
前端·javascript·后端
用户900463370401 小时前
5MB vs 4KB vs 无限大:浏览器存储谁更强?
前端
小小小小宇1 小时前
Harness Engineering 全解析与应用
前端
牧艺2 小时前
cos-design v3.0:从 15 个 Demo 到 49 个组件的视觉特效库
前端·视觉设计