关于 uniapp-frontend
uniapp-frontend 是使用 uni-app、Vue 3 和 TypeScript 构建跨平台应用的开发技能,提供页面、主题、UI 库、状态管理及平台构建方面的模式与指南。
主要功能
- 01页面与项目结构指南
- 02主题和 UI 库集成
- 03Pinia 状态管理模式
- 04API 与导航示例
- 05平台构建指南
- 06可复用页面与组件模板
适用场景
- 01创建 uni-app 页面并完成注册
- 02为应用添加多主题样式
- 03使用 Pinia 管理应用状态
- 04准备 H5 或 WeChat Mini Program 构建
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ enze00/ uniapp-frontend-skills --skill uniapp-frontend安装后在 Claude Code 中输入/uniapp-frontend确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
LICENSE.gitignoreREADME.mdassets/page-template.vuereferences/theme-guide.mdui-libraries.mdpage-patterns.md详细介绍
uni-app 前端开发
使用 uni-app、Vue 3 和 TypeScript 构建跨平台应用的综合指南。
快速开始
创建新页面
# Create page directory
mkdir -p src/pages/newpage
# Create page files
touch src/pages/newpage/index.vue
在 pages.json 中注册页面
{
"pages": [
{
"path": "pages/newpage/index",
"style": {
"navigationBarTitleText": "Page Title"
}
}
]
}
基础页面模板
完整的页面模板请参阅 assets/page-template.vue。
项目结构
标准的 uni-app CLI 项目结构:
src/
├── pages/ # Page components (one per directory)
├── components/ # Shared/reusable components
├── store/ # Pinia state management
├── api/ # API interface definitions
├── utils/ # Utility functions
├── types/ # TypeScript type definitions
├── styles/ # Global styles
│ ├── theme.scss # Theme variables
│ └── common.scss # Common styles
├── static/ # Static assets (images, icons)
├── App.vue # App root component
├── main.ts # App entry point
├── pages.json # Page and tabBar configuration
└── uni.scss # uni-app built-in variables
UI 库集成
uView Plus
安装:
npm install uview-plus
配置:
App.vue - 导入样式:
<style lang="scss">
@import "uview-plus/index.scss";
@import "@/styles/common.scss";
</style>
main.ts - 注册插件:
import uviewPlus from "uview-plus";
app.use(uviewPlus);
vite.config.ts - 全局 SCSS:
css: {
preprocessorOptions: {
scss: {
additionalData: `@import "@/styles/theme.scss";@import "uview-plus/theme.scss";`,
api: "modern-compiler",
},
},
}
其他 UI 库
uni-ui(官方):
npm install @dcloudio/uni-ui
TuniaoUI(Tuniao):
npm install @tuniao/tnui-vue3-uniapp
集成指南请参阅 references/ui-libraries.md。
主题系统设计
为多角色或多品牌应用实现灵活的主题配置。
基础主题设置
src/styles/theme.scss:
// Theme colors
$theme-primary: #1890ff;
$theme-success: #52c41a;
$theme-warning: #faad14;
$theme-error: #f5222d;
// Neutral colors
$color-text-primary: #333333;
$color-text-regular: #666666;
$color-text-secondary: #999999;
$color-bg-page: #f5f5f5;
$color-bg-card: #ffffff;
// Spacing scale
$spacing-xs: 8rpx;
$spacing-sm: 16rpx;
$spacing-md: 24rpx;
$spacing-lg: 32rpx;
$spacing-xl: 48rpx;
// Typography
$font-size-xs: 20rpx;
$font-size-sm: 24rpx;
$font-size-base: 28rpx;
$font-size-lg: 32rpx;
$font-size-xl: 36rpx;
// Border radius
$border-radius-sm: 4rpx;
$border-radius-md: 8rpx;
$border-radius-lg: 16rpx;
$border-radius-circle: 50%;
vite.config.ts - 全局注入:
css: {
preprocessorOptions: {
scss: {
additionalData: `@import "@/styles/theme.scss";`,
api: "modern-compiler",
},
},
}
多主题实现
对于需要多个主题的应用(例如用户端/管理端、不同品牌):
选项 1:为每个环境配置主题变量
// src/styles/theme.scss
// Define different theme color sets
$theme-user-primary: #1890ff;
$theme-admin-primary: #0050b3;
// Set active theme
$theme-primary: $theme-user-primary; // Change based on build/env
选项 2:动态切换主题
// store/theme.ts
import { defineStore } from 'pinia';
export const useThemeStore = defineStore('theme', {
state: () => ({
currentTheme: 'default',
}),
getters: {
themeColors() {
const themes = {
default: { primary: '#1890ff' },
dark: { primary: '#0050b3' },
};
return themes[this.currentTheme];
},
},
});
完整的主题配置模式请参阅 references/theme-guide.md。
构建命令
# WeChat Mini Program
npm run dev:mp-weixin # Development
npm run build:mp-weixin # Production
# H5
npm run dev:h5 # Development
npm run build:h5 # Production
# Other platforms
npm run dev:mp-alipay # Alipay Mini Program
npm run dev:mp-baidu # Baidu Mini Program
npm run dev:mp-toutiao # Toutiao Mini Program
常见模式
数据获取模式
<script setup lang="ts">
import { ref, onMounted } from "vue";
interface Item {
id: number;
title: string;
}
const items = ref<Item[]>([]);
const loading = ref(false);
const error = ref<string | null>(null);
onMounted(() => {
loadData();
});
const loadData = async () => {
loading.value = true;
error.value = null;
try {
const data = await api.getItems();
items.value = data;
} catch (err) {
error.value = "Failed to load data";
uni.showToast({ title: error.value, icon: "none" });
} finally {
loading.value = false;
}
};
</script>
导航模式
// Navigate to page (adds to history stack)
uni.navigateTo({ url: "/pages/detail/index" });
// Navigate with parameters
uni.navigateTo({ url: `/pages/detail/index?id=${id}&type=parcel` });
// Redirect (replaces current page, no back button)
uni.redirectTo({ url: "/pages/login/index" });
// Switch to tabBar page
uni.switchTab({ url: "/pages/home/index" });
// Navigate back
uni.navigateBack();
// Launch another mini program
uni.navigateToMiniProgram({
appId: "xxxxx",
path: "pages/index/index",
});
用户反馈
Toast:
uni.showToast({
title: "Success",
icon: "success",
duration: 2000,
});
uni.showToast({
title: "Error message",
icon: "none",
});
// Loading toast
uni.showLoading({ title: "Loading..." });
uni.hideLoading();
模态框:
uni.showModal({
title: "Confirm",
content: "Are you sure?",
success: (res) => {
if (res.confirm) {
// User clicked confirm
}
},
});
操作菜单:
uni.showActionSheet({
itemList: ["Option 1", "Option 2", "Option 3"],
success: (res) => {
console.log("Selected:", res.tapIndex);
},
});
生命周期钩子
<script setup lang="ts">
import {
onLaunch,
onShow,
onHide,
onUnload,
} from "@dcloudio/uni-app";
import { onLoad, onReady, onReachBottom, onPullDownRefresh } from "@dcloudio/uni-app";
// App-level hooks (use in App.vue)
onLaunch(() => {
console.log("App launched");
});
onShow(() => {
console.log("App shown");
});
// Page-level hooks (use in pages)
onLoad((options) => {
console.log("Page loaded with params:", options);
});
onReady(() => {
console.log("Page ready");
});
onReachBottom(() => {
console.log("Reached bottom - load more");
});
onPullDownRefresh(() => {
console.log("Pull down refresh");
// Stop loading after data fetch
uni.stopPullDownRefresh();
});
</script>
平台检测
// Get platform info
const systemInfo = uni.getSystemInfoSync();
console.log("Platform:", systemInfo.platform); // ios, android, devtools
console.log("System:", systemInfo.system); // iOS 14.5, Android 10
// Conditional code based on platform
// #ifdef H5
console.log("Running on H5");
// #endif
// #ifdef MP-WEIXIN
console.log("Running on WeChat Mini Program");
// #endif
// #ifdef MP-ALIPAY
console.log("Running on Alipay Mini Program");
// #endif
Pinia 状态管理
Store 定义:
// src/store/user.ts
import { defineStore } from 'pinia';
export const useUserStore = defineStore('user', {
state: () => ({
userInfo: null,
token: '',
}),
getters: {
isLoggedIn: (state) => !!state.token,
},
actions: {
async login(credentials) {
const data = await api.login(credentials);
this.token = data.token;
this.userInfo = data.user;
},
logout() {
this.token = '';
this.userInfo = null;
},
},
});
在组件中使用:
<script setup lang="ts">
import { useUserStore } from "@/store/user";
const userStore = useUserStore();
// Access state
console.log(userStore.userInfo);
// Call actions
await userStore.login({ username, password });
// Use getters
if (userStore.isLoggedIn) {
// ...
}
</script>
API 集成
API 模块:
// src/api/index.ts
const BASE_URL = "https://api.example.com";
export const api = {
// GET request
async getItems() {
const res = await uni.request({
url: `${BASE_URL}/items`,
method: "GET",
});
return res.data;
},
// POST request
async createItem(data: any) {
const res = await uni.request({
url: `${BASE_URL}/items`,
method: "POST",
data,
});
return res.data;
},
};
使用拦截器:
// src/utils/request.ts
let token = "";
export const request = (options: UniApp.RequestOptions) => {
// Add token
if (token) {
options.header = {
...options.header,
Authorization: `Bearer ${token}`,
};
}
return uni.request(options);
};
// Set token after login
export const setToken = (newToken: string) => {
token = newToken;
};
故障排查
未找到 SCSS 变量
错误: Undefined variable $spacing-md
解决方案:
- 检查
vite.config.ts是否配置了additionalData - 确认主题文件路径正确
- 修改配置后重启开发服务器
组件未渲染
检查项:
- 组件已在
pages.json中注册 - 导入路径正确(使用
@/别名) - Vue 组件名称采用 PascalCase 格式
构建错误
常见修复方法:
- 清除缓存:
rm -rf node_modules dist && npm install - 检查 Node.js 版本(使用 LTS 版本)
- 确认依赖项彼此兼容
平台特定问题
微信小程序:
- 确保
manifest.json中的 appid 正确 - 检查小程序管理后台中的域名白名单
- 在微信开发者工具中测试
H5:
- 在多个浏览器中测试
- 检查 CORS 配置
- 确认 API 端点支持 HTTPS
资源
references/theme-guide.md
包含多主题模式、色彩理论和实现策略的完整主题系统设计指南。
references/ui-libraries.md
uView Plus、uni-ui、TuniaoUI 及其他常用 UI 库的集成指南。
references/page-patterns.md
可复用的页面模式:列表页、详情页、表单、搜索/筛选、空状态等。
references/platform-specific.md
微信、支付宝、H5 等平台的注意事项和最佳实践。
assets/page-template.vue
可直接自定义的精简 Vue 3 + TypeScript 页面模板。
assets/component-templates/
常用组件模板(卡片、按钮组、列表项等)。
最佳实践
- 使用 TypeScript - 在编译时发现错误
- 组件组合 - 保持组件小巧且专注
- 状态管理 - 复杂状态使用 Pinia
- 错误处理 - 始终妥善处理 API 错误
- 加载状态 - 异步操作期间显示加载指示器
- 响应式设计 - 在多种屏幕尺寸上测试
- 性能 - 延迟加载图片和长列表
- 无障碍访问 - 使用语义化 HTML 和 ARIA 标签
- 代码组织 - 遵循一致的文件结构
- 版本控制 - 经常提交,并使用有意义的提交信息