第一个Ionic应用 #
一、创建项目 #
1.1 选择项目模板 #
Ionic提供多种项目模板:
| 模板 | 说明 |
|---|---|
| blank | 空白项目 |
| tabs | 带底部标签页 |
| sidemenu | 带侧边菜单 |
| super | 完整示例项目 |
| tutorial | 教程项目 |
| conference | 会议应用示例 |
1.2 创建项目 #
Angular项目:
bash
# 创建空白项目
ionic start myApp blank --type=angular
# 创建带标签页的项目
ionic start myApp tabs --type=angular
# 创建带侧边菜单的项目
ionic start myApp sidemenu --type=angular
React项目:
bash
# 创建React项目
ionic start myApp blank --type=react
# 创建带标签页的项目
ionic start myApp tabs --type=react
Vue项目:
bash
# 创建Vue项目
ionic start myApp blank --type=vue
# 创建带标签页的项目
ionic start myApp tabs --type=vue
1.3 项目创建选项 #
bash
# 完整创建命令
ionic start myApp tabs --type=angular \
--capacitor \
--package-id=com.example.myapp
# 参数说明
# --type 指定框架类型
# --capacitor 集成Capacitor
# --package-id 指定应用包名
二、项目结构 #
2.1 Angular项目结构 #
text
myApp/
├── src/
│ ├── app/
│ │ ├── app.component.ts # 根组件
│ │ ├── app.component.html # 根模板
│ │ ├── app.component.scss # 根样式
│ │ ├── app.module.ts # 根模块
│ │ ├── app-routing.module.ts # 路由配置
│ │ └── home/ # 首页模块
│ │ ├── home.module.ts
│ │ ├── home.page.ts
│ │ ├── home.page.html
│ │ └── home.page.scss
│ ├── assets/ # 静态资源
│ ├── environments/ # 环境配置
│ ├── theme/ # 主题样式
│ │ └── variables.scss # CSS变量
│ ├── global.scss # 全局样式
│ ├── index.html # 入口HTML
│ └── main.ts # 入口脚本
├── angular.json # Angular配置
├── ionic.config.json # Ionic配置
├── package.json # 项目依赖
├── tsconfig.json # TypeScript配置
└── capacitor.config.ts # Capacitor配置
2.2 React项目结构 #
text
myApp/
├── src/
│ ├── components/ # 组件目录
│ ├── pages/ # 页面目录
│ ├── theme/ # 主题样式
│ ├── App.tsx # 根组件
│ ├── App.css # 根样式
│ └── main.tsx # 入口文件
├── public/ # 公共资源
├── ionic.config.json # Ionic配置
├── package.json # 项目依赖
└── capacitor.config.ts # Capacitor配置
2.3 Vue项目结构 #
text
myApp/
├── src/
│ ├── components/ # 组件目录
│ ├── views/ # 页面目录
│ ├── router/ # 路由配置
│ ├── theme/ # 主题样式
│ ├── App.vue # 根组件
│ └── main.ts # 入口文件
├── public/ # 公共资源
├── ionic.config.json # Ionic配置
├── package.json # 项目依赖
└── capacitor.config.ts # Capacitor配置
三、开发首页 #
3.1 创建首页(Angular) #
生成页面:
bash
# 使用CLI生成页面
ionic generate page home
# 或简写
ionic g page home
页面组件(home.page.ts):
typescript
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
standalone: true,
imports: [CommonModule]
})
export class HomePage {
items = [
{ id: 1, title: '项目一', description: '这是第一个项目' },
{ id: 2, title: '项目二', description: '这是第二个项目' },
{ id: 3, title: '项目三', description: '这是第三个项目' }
];
constructor() {}
onItemClick(item: any) {
console.log('点击了:', item);
}
}
页面模板(home.page.html):
html
<ion-header>
<ion-toolbar>
<ion-title>
我的应用
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<ion-item
*ngFor="let item of items"
(click)="onItemClick(item)"
button
>
<ion-label>
<h2>{{ item.title }}</h2>
<p>{{ item.description }}</p>
</ion-label>
</ion-item>
</ion-list>
</ion-content>
3.2 创建首页(React) #
页面组件(Home.tsx):
tsx
import React, { useState } from 'react';
import {
IonContent,
IonHeader,
IonPage,
IonTitle,
IonToolbar,
IonList,
IonItem,
IonLabel
} from '@ionic/react';
interface Item {
id: number;
title: string;
description: string;
}
const Home: React.FC = () => {
const [items] = useState<Item[]>([
{ id: 1, title: '项目一', description: '这是第一个项目' },
{ id: 2, title: '项目二', description: '这是第二个项目' },
{ id: 3, title: '项目三', description: '这是第三个项目' }
]);
const onItemClick = (item: Item) => {
console.log('点击了:', item);
};
return (
<IonPage>
<IonHeader>
<IonToolbar>
<IonTitle>我的应用</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent>
<IonList>
{items.map(item => (
<IonItem
key={item.id}
button
onClick={() => onItemClick(item)}
>
<IonLabel>
<h2>{item.title}</h2>
<p>{item.description}</p>
</IonLabel>
</IonItem>
))}
</IonList>
</IonContent>
</IonPage>
);
};
export default Home;
3.3 创建首页(Vue) #
页面组件(Home.vue):
vue
<template>
<ion-page>
<ion-header>
<ion-toolbar>
<ion-title>我的应用</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<ion-item
v-for="item in items"
:key="item.id"
button
@click="onItemClick(item)"
>
<ion-label>
<h2>{{ item.title }}</h2>
<p>{{ item.description }}</p>
</ion-label>
</ion-item>
</ion-list>
</ion-content>
</ion-page>
</template>
<script setup lang="ts">
import { ref } from 'vue';
interface Item {
id: number;
title: string;
description: string;
}
const items = ref<Item[]>([
{ id: 1, title: '项目一', description: '这是第一个项目' },
{ id: 2, title: '项目二', description: '这是第二个项目' },
{ id: 3, title: '项目三', description: '这是第三个项目' }
]);
const onItemClick = (item: Item) => {
console.log('点击了:', item);
};
</script>
四、添加功能 #
4.1 添加搜索功能 #
Angular示例:
typescript
// home.page.ts
export class HomePage {
items = [...];
filteredItems = [...this.items];
searchTerm = '';
filterItems() {
this.filteredItems = this.items.filter(item =>
item.title.toLowerCase().includes(this.searchTerm.toLowerCase())
);
}
}
html
<!-- home.page.html -->
<ion-header>
<ion-toolbar>
<ion-title>我的应用</ion-title>
</ion-toolbar>
<ion-toolbar>
<ion-searchbar
[(ngModel)]="searchTerm"
(ionInput)="filterItems()"
placeholder="搜索..."
></ion-searchbar>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<ion-item
*ngFor="let item of filteredItems"
(click)="onItemClick(item)"
button
>
<ion-label>
<h2>{{ item.title }}</h2>
<p>{{ item.description }}</p>
</ion-label>
</ion-item>
</ion-list>
</ion-content>
4.2 添加下拉刷新 #
html
<ion-content>
<ion-refresher slot="fixed" (ionRefresh)="doRefresh($event)">
<ion-refresher-content></ion-refresher-content>
</ion-refresher>
<ion-list>
<!-- 列表内容 -->
</ion-list>
</ion-content>
typescript
// Angular
doRefresh(event: any) {
setTimeout(() => {
this.loadData();
event.target.complete();
}, 1000);
}
// React
const doRefresh = (event: CustomEvent) => {
setTimeout(() => {
loadData();
event.detail.complete();
}, 1000);
};
// Vue
const doRefresh = (event: any) => {
setTimeout(() => {
loadData();
event.target.complete();
}, 1000);
};
4.3 添加无限滚动 #
html
<ion-content>
<ion-list>
<ion-item *ngFor="let item of items">
{{ item.title }}
</ion-item>
</ion-list>
<ion-infinite-scroll (ionInfinite)="loadMore($event)">
<ion-infinite-scroll-content></ion-infinite-scroll-content>
</ion-infinite-scroll>
</ion-content>
typescript
loadMore(event: any) {
setTimeout(() => {
this.items.push(...this.getMoreItems());
event.target.complete();
if (this.items.length >= 100) {
event.target.disabled = true;
}
}, 500);
}
五、运行应用 #
5.1 Web浏览器运行 #
bash
# 启动开发服务器
ionic serve
# 指定端口
ionic serve --port 8200
# 外部访问
ionic serve --external
# 打开浏览器
ionic serve --open
开发服务器选项:
| 选项 | 说明 |
|---|---|
--port |
指定端口 |
--external |
允许外部访问 |
--lab |
打开Ionic Lab |
--open |
自动打开浏览器 |
5.2 Ionic Lab #
bash
# 启动Ionic Lab
ionic serve --lab
# 或单独启动
ionic lab
Ionic Lab可以同时预览iOS和Android效果。
5.3 iOS模拟器运行 #
bash
# 添加iOS平台
ionic cap add ios
# 构建项目
ionic build
# 同步到原生项目
npx cap sync ios
# 运行iOS模拟器
ionic cap run ios
# 指定模拟器
ionic cap run ios --target="iPhone-14"
# 热重载
ionic cap run ios -l --external
5.4 Android模拟器运行 #
bash
# 添加Android平台
ionic cap add android
# 构建项目
ionic build
# 同步到原生项目
npx cap sync android
# 运行Android模拟器
ionic cap run android
# 指定设备
ionic cap run android --target="Pixel_4_API_33"
# 热重载
ionic cap run android -l --external
5.5 真机运行 #
iOS真机:
bash
# 连接iPhone
# 运行到真机
ionic cap run ios --device
# 或打开Xcode手动运行
npx cap open ios
Android真机:
bash
# 开启USB调试
# 运行到真机
ionic cap run android --device
# 或打开Android Studio手动运行
npx cap open android
六、调试技巧 #
6.1 浏览器调试 #
bash
# 启动开发服务器
ionic serve
# 打开Chrome DevTools
# 快捷键: F12 或 Cmd+Option+I (Mac)
6.2 iOS调试 #
Safari Web Inspector:
- iPhone: 设置 → Safari → 高级 → Web检查器
- 连接iPhone到Mac
- Safari → 开发 → [你的iPhone] → [你的应用]
Chrome DevTools:
bash
# 热重载模式
ionic cap run ios -l --external
# 在Chrome打开
# chrome://inspect
6.3 Android调试 #
Chrome DevTools:
- 连接Android设备或启动模拟器
- 打开 chrome://inspect
- 找到你的WebView并点击inspect
bash
# 热重载模式
ionic cap run android -l --external
6.4 控制台日志 #
typescript
// 使用console.log
console.log('调试信息:', data);
// 使用console.error
console.error('错误信息:', error);
// 使用console.warn
console.warn('警告信息:', warning);
七、生成器命令 #
7.1 页面生成 #
bash
# 生成页面
ionic generate page detail
# 简写
ionic g page detail
# 指定模块
ionic g page detail --module=app
7.2 组件生成 #
bash
# 生成组件
ionic generate component my-component
# 简写
ionic g component my-component
7.3 服务生成 #
bash
# 生成服务
ionic generate service services/user
# 简写
ionic g service services/user
7.4 其他生成器 #
bash
# 生成指令
ionic g directive directives/highlight
# 生成管道
ionic g pipe pipes/filter
# 生成守卫
ionic g guard guards/auth
八、常见问题 #
8.1 端口被占用 #
bash
# 查找占用端口的进程
lsof -i :8100
# 杀掉进程
kill -9 [PID]
# 或使用其他端口
ionic serve --port 8200
8.2 模拟器启动失败 #
bash
# iOS模拟器
# 重置模拟器
xcrun simctl shutdown all
xcrun simctl erase all
# Android模拟器
# 冷启动模拟器
emulator -avd MyDevice -no-snapshot-load
8.3 热重载不工作 #
bash
# 清除缓存
rm -rf node_modules
npm install
# 重启开发服务器
ionic serve
8.4 原生插件问题 #
bash
# 重新同步
npx cap sync
# 清除原生项目
rm -rf ios android
ionic cap add ios
ionic cap add android
九、最佳实践 #
9.1 代码组织 #
text
src/
├── app/
│ ├── core/ # 核心模块
│ │ ├── services/ # 服务
│ │ ├── guards/ # 路由守卫
│ │ └── interceptors/ # HTTP拦截器
│ ├── shared/ # 共享模块
│ │ ├── components/ # 共享组件
│ │ ├── directives/ # 共享指令
│ │ └── pipes/ # 共享管道
│ ├── features/ # 功能模块
│ │ ├── home/
│ │ ├── detail/
│ │ └── settings/
│ └── app.module.ts
9.2 命名规范 #
| 类型 | 规范 | 示例 |
|---|---|---|
| 页面 | xxx.page.ts | home.page.ts |
| 组件 | xxx.component.ts | user-card.component.ts |
| 服务 | xxx.service.ts | user.service.ts |
| 模块 | xxx.module.ts | home.module.ts |
9.3 性能优化 #
typescript
// 使用OnPush变更检测
@Component({
changeDetection: ChangeDetectionStrategy.OnPush
})
// 使用懒加载
const routes: Routes = [
{
path: 'detail',
loadChildren: () => import('./detail/detail.module')
.then(m => m.DetailPageModule)
}
];
// 使用虚拟滚动
<ion-virtual-scroll [items]="items">
<ion-item *virtualItem="let item">
{{ item.name }}
</ion-item>
</ion-virtual-scroll>
十、总结 #
10.1 关键步骤回顾 #
- 使用
ionic start创建项目 - 了解项目结构
- 开发页面和组件
- 使用
ionic serve运行 - 添加原生平台并运行
10.2 下一步 #
现在你已经创建了第一个Ionic应用,接下来让我们深入了解 项目结构,学习更多Ionic开发技巧!
最后更新:2026-03-28