基于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演示

相关推荐
拳打南山敬老院15 分钟前
Context 不是压缩出来的,而是设计出来的
前端·后端·aigc
用户30767528112719 分钟前
💡 从"傻等"到"流淌":我在AI项目中实现流式输出的血泪史(附真实代码+深度解析)
前端
bluceli20 分钟前
前端性能优化实战指南:让你的网页飞起来
前端·性能优化
UIUV20 分钟前
RAG技术学习笔记(含实操解析)
javascript·langchain·llm
SuperEugene22 分钟前
Vue状态管理扫盲篇:如何设计一个合理的全局状态树 | 用户、权限、字典、布局配置
前端·vue.js·面试
没想好d23 分钟前
通用管理后台组件库-9-高级表格组件
前端
阿虎儿26 分钟前
React Hook 入门指南
前端·react.js
阿懂在掘金1 小时前
defineModel 是进步还是边界陷阱?双数据源组件的选择逻辑
vue.js·源码阅读
核以解忧1 小时前
借助VTable Skill实现10W+数据渲染
前端
WangHappy1 小时前
不写 Canvas 也能搞定!小程序图片导出的 WebView 通信方案
前端·微信小程序