DIY 自定义页面使用指南
本项目包含一套基于 JSON 数据驱动的 DIY 页面渲染系统,允许通过后台配置动态生成页面内容。
1. 核心架构
- 数据驱动: 页面结构由 JSON 数据描述(
pageContentData),包含组件列表及其配置。 - 动态渲染:
src/components/diy/index.vue遍历组件列表,根据type字段动态渲染对应的子组件。 - 通用样式:
useDiyStyle钩子统一处理边距、圆角、背景等通用样式。
2. 页面结构
2.1 渲染入口 (DiyPage)
所有 DIY 页面都通过 src/components/diy/index.vue 进行渲染。它接收两个核心 Prop:
pageContentData: 页面配置数据,包含components数组。pageName: 页面标题。
html
<diy-page :page-content-data="pageContent" :page-name="pageName" />2.2 支持的组件类型
目前支持以下组件类型(对应 type 字段):
类型 (type) | 组件 | 说明 |
|---|---|---|
notice | diy-notice | 公告栏 |
goods | diy-goods | 商品列表(支持手动选择或自动获取) |
image-ad | diy-image | 图片广告/轮播图 |
title-text | diy-title-text | 标题文本 |
rich-text | diy-rich-text | 富文本 |
gap | diy-gap | 辅助空白 |
3. 开发新组件
如果需要新增 DIY 组件,请遵循以下步骤:
3.1 创建组件
在 src/components/diy/ 目录下创建新文件夹(如 diy-new),并新建 index.vue。
vue
<script setup lang="ts">
import { computed } from 'vue'
import { useDiyStyle } from '@/composables/useDiyStyle'
// 1. 接收 showData 参数
const props = defineProps({
showData: {
type: Object,
default: () => ({}),
},
})
// 2. 使用通用样式钩子
const dynamicStyles = useDiyStyle(computed(() => props.showData.commonStyle))
</script>
<template>
<!-- 3. 应用样式并渲染内容 -->
<view :style="dynamicStyles">
{{ showData.someField }}
</view>
</template>3.2 注册组件
在 src/components/diy/index.vue 中引入并注册新组件。
引入组件:
typescriptimport DiyNew from '@/components/diy/diy-new/index.vue'添加模板分支:
html<template v-if="item.type === 'new-type'"> <diy-new :show-data="item.formData" /> </template>
4. 数据来源与 API
DIY 页面数据通常由后端 API 提供。
- 接口文件:
src/api/promotion/pageDesign.ts - 获取详情:
getById(id)获取页面设计详情。
示例:加载 DIY 页面
在页面中加载数据的典型逻辑(参考 src/sub-pages/promotion/diy-page/index.vue):
typescript
import { getById } from '@/api/promotion/pageDesign'
const pageContent = ref()
async function loadDiyPage(id) {
const res = await getById(id)
// 后端返回的 pageContent 是 JSON 字符串,需解析
pageContent.value = JSON.parse(res.pageContent)
}5. 样式处理 (useDiyStyle)
为了保持所有 DIY 组件样式配置的一致性,请务必使用 useDiyStyle。它会将后端返回的样式配置对象转换为 CSS 样式对象。
支持的通用样式属性:
- 外边距 (Margin): Top, Bottom, Left, Right
- 内边距 (Padding): Top, Bottom, Left, Right
- 圆角 (Radius): TopLeft, TopRight, BottomLeft, BottomRight
- 背景 (Background): 颜色、渐变、图片
6. 路由跳转
DIY 组件内部通常需要跳转链接,建议使用封装好的跳转方法。
typescript
import { toJumpUrl } from '@/utils/index'
function handleClick() {
// 假设 link 是后端配置的跳转路径
if (props.showData.link) {
// 处理跳转逻辑
toJumpUrl(props.showData.link.url)
}
}