开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第22天,点击查看活动详情
前言
使用 uniapp 开发项目时,有时候需要根据自己项目的需要自定义自己的页面模板,通常会包含一个统一的根页面组件,以方便保持全局样式的一致,更利于兼容处理,项目维护
全局引入页面组件
uniapp支持配置方式全局引入组件,也支持使用 vue 传统的组件注册方式,本编主要讲下官方配置方式引入应该如何配置
创建组件目录
这里我创建一个common目录来存放全局使用的组件
common
└── sf-page
└── sf-page.vue
这里需要注意文件的命名,组件目录与组件名称保持一致
修改配置文件
修改 pages.json,这里使用 sf- 作为自定义组件前缀
{
"easycom": {
"autoscan": true,
"custom": {
// uni-ui 规则如下配置
"^uni-(.*)": "@dcloudio/uni-ui/lib/uni-$1/uni-$1.vue",
"^sf-(.*)": "@/common/sf-$1/sf-$1.vue"
}
}
}
最好此时重启下项目,就可以直接在项目中使用注册的组件标签了
<template>
<sf-page>
// ...
</sf-page>
</template>
页面组件开发
需求
自定义的页面组件,需要满足我们一下功能配置
- 可配置化控制
header / body / footer三块区域 - 支持主题配置
开发
- 页面结构划分与主题样式配置
关于主题可参考该篇 juejin.cn/post/717471…
<template>
<view class="sf-page" :class="theme">
<!-- 页面头部 -->
<view v-if="customHeader" class="">
<slot name="header"></slot>
</view>
<!-- 页面主体 -->
<view class="">
<slot name="body"></slot>
</view>
<!-- 页面底部 -->
<view v-if="customFooter" class="">
<slot name="footer"></slot>
</view>
</view>
</template>
<script setup>
import { computed } from "vue";
const props = defineProps({
customHeader: {
type: Boolean,
default: false
},
customFooter: {
type: Boolean,
default: false
},
})
const theme = computed(() => {
return uni.$theme.get()
})
</script>
<style>
</style>
组件使用
<template>
<sf-page :customHeader="false" :customFooter="false">
<template v-slot:header></template>
<template v-slot:body>
<view class="theme-bg">
<text>测试</text>
</view>
</template>
<template v-slot:footer></template>
</sf-page>
</template>
自定义模板
配置模板文件是为了我们使用 uniapp 的新建页面时,可以使用我们想要的页面模板进行初始化
编辑模板文件
<template>
<sf-page :customHeader="false" :customFooter="false">
<template v-slot:header></template>
<template v-slot:body>
</template>
<template v-slot:footer></template>
</sf-page>
</template>
<script setup>
</script>
<style lang="scss">
</style>
设置自定义模板
在 hbuilder 项目中右键新建页面,点击自定义模板
点击后会打开文件目录,将模板文件复制到该目录下,下次新建页面时就可以看到我们的自定义模板了
再次新建页面
好了,到此我们就已经把自定义 uniapp 页面模板的配置弄好啦