page-development.md
3.01 KB
页面开发指南
本文档介绍如何在项目中添加新页面。
目录结构
所有页面遵循以下目录结构:
src/pages/your-page/
├── index.vue # 页面组件(必须使用 <script setup>)
├── index.config.js # 页面配置(navigationBarTitleText 等)
└── assets/ # 页面特定资源(可选)
步骤 1:创建页面目录和文件
mkdir -p src/pages/your-page
touch src/pages/your-page/index.vue
touch src/pages/your-page/index.config.js
步骤 2:配置页面
index.config.js:
export default {
navigationBarTitleText: '您的页面标题',
enablePullDownRefresh: true,
backgroundColor: '#f5f5f5'
}
步骤 3:编写页面组件
index.vue:
<script setup>
import { ref } from 'vue'
import { useLoad, useShow } from '@tarojs/taro'
const pageId = ref(null)
useLoad((options) => {
console.log('页面加载,参数:', options)
// 接收导航参数
if (options.id) {
pageId.value = options.id
// 根据 ID 获取数据
}
})
useShow(() => {
console.log('页面显示')
})
// 您的组件逻辑
</script>
<template>
<view class="page">
<!-- 页面内容 -->
</view>
</template>
<style lang="less" scoped>
.page {
padding: 20px;
}
</style>
步骤 4:注册路由
在 src/app.config.js 中注册路由:
export default {
pages: [
'pages/your-page/index',
// ... 其他页面
],
// ...
}
步骤 5:添加导航(可选)
使用 useGo Hook(推荐)
import { useGo } from '@/hooks/useGo'
const go = useGo()
// 带查询参数导航
go('/pages/your-page/index', { id: 123, type: 'insurance' })
使用 Taro 内置导航
import Taro from '@tarojs/taro'
Taro.navigateTo({
url: '/pages/your-page/index?id=123'
})
接收导航参数
在目标页面的 useLoad 中接收参数:
useLoad((options) => {
console.log('接收到的参数:', options)
const { id, type } = options
// 根据参数获取数据
fetchData(id, type)
})
TabBar 集成(可选)
如果页面需要底部导航栏:
- 导入
TabBar组件 - 根据路由配置激活状态
<script setup>
import TabBar from '@/components/TabBar.vue'
</script>
<template>
<view class="page">
<!-- 页面内容 -->
<TabBar />
</view>
</template>
常见问题
Q: 页面注册后还是 404?
A: 检查以下几点:
- 路由路径是否正确(
pages/your-page/index) - 是否重启了开发服务器
-
index.config.js是否存在
Q: 如何隐藏原生导航栏?
A: 在 index.config.js 中设置:
export default {
navigationStyle: 'custom'
}
Q: 页面参数丢失?
A: 检查参数是否正确编码:
// ❌ 错误
go('/pages/detail/index', { id: '123' })
// ✅ 正确
go('/pages/detail/index', { id: 123 }) // 数字类型
// 或
go('/pages/detail/index?id=123') // 字符串类型