Skip to main content

Ionic Vue 快速入门

什么是 Ionic 框架?

¥What is Ionic Framework?

首先,如果你是新来的,欢迎!Ionic Framework 是一个免费的开源组件库,用于构建在 iOS、Android、Electron 和 Web 上运行的应用。使用熟悉的技术(HTML、CSS、JavaScript)编写一次应用并部署到任何平台。

¥First off, if you're new here, welcome! Ionic Framework is a free and open source component library for building apps that run on iOS, Android, Electron, and the Web. Write your app once using familiar technologies (HTML, CSS, JavaScript) and deploy to any platform.

除了 UI 组件之外,Ionic Framework 还提供了一个命令行工具,用于创建新应用以及部署到我们支持的各种平台。

¥Along with the UI components, Ionic Framework also provides a command line tool for creating new apps, as well as deploying to the various platforms we support.

在本指南中,我们将介绍 Vue 和 Ionic Framework 的基础知识,包括任何 Ionic Framework 的特定功能。如果你熟悉 Vue,请享受该指南并了解有关 Ionic Framework 的新知识。如果你对其中任何一个都不熟悉,不用担心!本指南将涵盖基础知识并提供足够的信息来启动和运行应用。

¥In this guide, we will go over the basics of both Vue and Ionic Framework, including any Ionic Framework specific features. If you are familiar with Vue, enjoy the guide and learn something new about Ionic Framework. If you are not familiar with either, no worries! This guide will cover the basics and provide enough information to get an app up and running.

使用 Ionic CLI 创建项目

¥Creating a project with the Ionic CLI

首先,让我们安装最新版本的 Ionic CLI。

¥To get started, let's install the latest version of the Ionic CLI.

npm install -g @ionic/cli@latest

从这里开始,全局命令 ionic 将允许使用 Ionic Framework 和任何其他依赖创建 Vue 项目。要创建新项目,请运行以下命令:

¥From here, the global command ionic will allow for the creation of a Vue project with Ionic Framework and any other dependencies. To create a new project, run the following command:

ionic start myApp blank --type vue
cd myApp

从这里,我们运行 ionic serve 并让我们的项目在浏览器中运行。

¥From here, we run ionic serve and have our project running in the browser.

使用 TypeScript 或 JavaScript 构建你的方式

¥Build your way with TypeScript or JavaScript

我们喜欢 Ionic 的 TypeScript,并且长期以来一直相信它是构建可扩展应用的绝佳工具。也就是说,我们知道 Vue 社区在工具、语言等方面非常重视简单性。事实上,这很可能是吸引你使用 Vue 的首要原因。从简单开始 - 然后根据需要扩大规模。

¥We love TypeScript at Ionic, and have believed for quite some time now that it’s a great tool for building scalable apps. That said, we know how much the Vue community values simplicity – in their tooling, languages, and more. In fact, it’s likely what drew you to Vue in the first place. Start simple – then scale up as needed.

因此,如果你更喜欢使用 JavaScript 而不是 TypeScript,也可以。生成 Ionic Vue 应用后,请按照以下步骤操作:

¥So, if you’d prefer to use JavaScript instead of TypeScript, you can. After generating an Ionic Vue app, follow these steps:

  1. 删除 TypeScript 依赖:

    ¥Remove TypeScript dependencies:

npm uninstall --save typescript @types/jest @typescript-eslint/eslint-plugin @typescript-eslint/parser @vue/cli-plugin-typescript @vue/eslint-config-typescript vue-tsc
  1. 将所有 .ts 文件更改为 .js。在空白的 Ionic Vue 应用中,这应该只是 src/router/index.tssrc/main.ts。如果你使用测试,还需更改 tests 目录中文件的扩展名。

    ¥Change all .ts files to .js. In a blank Ionic Vue app, this should only be src/router/index.ts and src/main.ts. If you're using tests, also change the extension of files in the tests directory.

  2. index.html 中,将导入的 <script> 文件从 /src/main.ts 更改为 /src/main.js

    ¥In index.html, change the imported <script> file from /src/main.ts to /src/main.js.

  3. .eslintrc.js 中删除 @vue/typescript/recommended@typescript-eslint/no-explicit-any: ‘off’,

    ¥Remove @vue/typescript/recommended and @typescript-eslint/no-explicit-any: ‘off’, from .eslintrc.js.

  4. 删除 Array<RouteRecordRaw> 并从 src/router/index.js 中删除 RouteRecordRaw 的导入。

    ¥Remove Array<RouteRecordRaw> and the import of RouteRecordRaw from src/router/index.js.

  5. 删除 src/shims-vue.d.ts 文件(如果存在)。仅当使用 Vue CLI 时才需要这样做。

    ¥Delete the src/shims-vue.d.ts file if it exists. This is only needed when using the Vue CLI.

  6. 从任何具有 script 标签的 Vue 组件中删除 lang="ts"。在空白的 Ionic Vue 应用中,这应该只是 src/App.vuesrc/views/HomePage.vue

    ¥Remove lang="ts" from the script tags in any of your Vue components that have them. In a blank Ionic Vue app, this should only be src/App.vue and src/views/HomePage.vue.

  7. 删除 tsconfig.json 文件。

    ¥Delete the tsconfig.json file.

  8. 在 package.json 中,将构建脚本从 "build": "vue-tsc && vite build" 更改为 "build": "vite build"

    ¥In package.json, change the build script from "build": "vue-tsc && vite build" to "build": "vite build"

  9. 安装 terser npm i -D terser

    ¥Install terser npm i -D terser.

看一下 Vue 组件

¥A look at a Vue Component

我们的应用的基础将位于 src 目录中,主入口点将是我们的 main.ts 文件。如果我们在代码编辑器中打开项目并打开 main.ts,我们应该看到以下内容:

¥The base of our app will be in the src directory, and the main entry point will be our main.ts file. If we open our project in a code editor and open main.ts, we should see the following:

import { createApp } from 'vue';


import { IonicVue } from '@ionic/vue';



import App from './App.vue';
import router from './router';

const app = createApp(App).use(IonicVue).use(router);

router.isReady().then(() => {
app.mount('#app');
});

那么这是怎么回事呢?前四行引入了一些依赖。createApp 函数让我们初始化 Vue 应用,而 IonicVue 是一个插件,允许我们在 Vue 环境中使用 Ionic Framework。

¥So what is going on here? The first four lines are pulling in some dependencies. The createApp function lets us initialize our Vue application, while IonicVue is a plugin that allows us to use Ionic Framework in a Vue environment.

第三个导入是我们应用的根组件,简单地命名为 App。这是我们的第一个 Vue 组件,将在我们的 Vue 应用的引导过程中使用。

¥The third import is the root component for our app, simply named App. This is our first Vue component and will be used in the bootstrapping process for our Vue app.

第四个导入获取我们的路由配置。稍后我们将更深入地讨论这一点。

¥The fourth import gets our routing configuration. We will look at this more in depth later.

如果我们打开 App.vue 我们应该看到以下内容:

¥If we open App.vue we should see the following:

<template>
<ion-app>
<ion-router-outlet />
</ion-app>
</template>

<script setup lang="ts">
import { IonApp, IonRouterOutlet } from '@ionic/vue';
</script>

让我们从导入开始分解它。

¥Let's break it down, starting with the imports.

<script setup lang="ts">
import { IonApp, IonRouterOutlet } from '@ionic/vue';
</script>

要在 Vue 中使用组件,必须首先导入它。因此,对于 Ionic Framework,这意味着任何时候我们想要使用按钮或卡片,都必须将其添加到我们的导入中。对于 App 组件,我们使用 IonAppIonRouterOutlet。Vue 的 script setup 语法 允许模板访问 <ion-app><ion-router-outlet> 等组件。

¥To use a component in Vue, you must first import it. So for Ionic Framework, this means anytime we want to use a Button or a Card, it must be added to our imports. In the case of our App component, we are using IonApp and IonRouterOutlet. Vue's script setup syntax gives the template access to those components as <ion-app> and <ion-router-outlet>.

如果你发现自己重复导入相同的组件,你还可以全局注册组件。这伴随着我们在 优化你的构建 中介绍的性能权衡。

¥You can also register components globally if you find yourself importing the same components repeatedly. This comes with performance tradeoffs that we cover in Optimizing Your Build.

从这里开始,让我们看看模板。

¥From there, let's look at the template.

<template>
<ion-app>
<ion-router-outlet />
</ion-app>
</template>

所有 Vue 组件都必须有 <template>。在里面,我们放置了 IonAppIonRouterOutlet 组件。

¥All Vue components must have a <template>. Inside of there, we place our IonApp and IonRouterOutlet components.

初始化路由

¥Initializing the router

Ionic Vue 使用 vue-router 依赖,因此如果你已经熟悉 Vue Router,你将能够将你所知道的知识应用于 Ionic Vue 中的导航。我们来看看之前提到的路由配置。在 router/index.ts 中,你应该看到类似以下内容的内容:

¥Ionic Vue uses the vue-router dependency, so if you are already familiar with Vue Router, you will be able to apply what you know to navigation in Ionic Vue. Let's take a look at the router configuration we mentioned before. In router/index.ts, you should see something similar to the following:



import { createRouter, createWebHistory } from '@ionic/vue-router';


import { RouteRecordRaw } from 'vue-router';


import HomePage from '@/views/HomePage.vue';



const routes: Array<RouteRecordRaw> = [
{
path: '/',
redirect: '/home',
},
{
path: '/home',
name: 'Home',
component: HomePage,
},
];

const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
});

export default router;
注意

此示例使用 Ionic Vue Blank 入门应用,因此你的实际路由可能看起来有点不同。

¥This example is using the Ionic Vue Blank starter application, so your actual routes may look a bit different.

这里的设置与直接使用 vue-router 相同,但你需要从 @ionic/vue-router 包导入 createRoutercreateWebHistory 等依赖。

¥The setup here is the same as if you were using vue-router directly, but instead you need to import dependencies such as createRouter and createWebHistory from the @ionic/vue-router package.

导入依赖后,我们可以在 routes 数组中声明我们的路由。从那里,我们可以创建一个路由实例,并为其提供我们的路由和我们想要使用的历史记录类型。

¥After importing our dependencies, we can declare our routes in the routes array. From there, we can create a router instance and provide it with our routes and the type of history we want to use.

使用 Ionic Vue,延迟加载可以开箱即用。除了导入 Home 组件之外,我们还可以这样做:

¥With Ionic Vue, lazy loading works right out of the box. Instead of importing our Home component, we could also do:

const routes: Array<RouteRecordRaw> = [
{
path: '/',
redirect: '/home',
},
{
path: '/home',
name: 'Home',
component: () => import('@/views/HomePage.vue'),
},
];

现在,你可能想知道:为什么我们在描述组件路径时使用 @@ 符号是我们可以用来描述相对于 src 目录的路径的快捷方式。如果我们尝试在多个文件夹深度的文件中引用组件,这非常有用。我们可以简单地执行 '@/views/HomePage.vue',而不是执行 '../../../views/HomePage.vue'

¥Now, you might be wondering: Why do we use @ when describing the path to our components? The @ symbol is a shortcut we can use to describe paths relative to the src directory. This is useful if we are trying to reference a component while in a file several folders deep. Instead of doing '../../../views/HomePage.vue', we could simply do '@/views/HomePage.vue'.

使用样式的组件

¥A component with style

现在 App 组件实际上没有太多需要修改的地方。它是容器组件的基本示例。设置好路由逻辑后,它所负责的就是渲染一个与给定 URL 路由匹配的组件。由于我们已经有了一个组件/路由设置,因此让我们继续修改 Home 组件。

¥Now the App component does not really have a lot to modify here. It is a basic example of a container component. With the router logic set, all it is responsible for is to render a component that matches the given URL route. Since we already have one component/router setup, let's go ahead and modify our Home component.

目前,Home 组件如下所示:

¥Currently, the Home component looks like so:

Vue home component

<template>
<ion-page>
<ion-header :translucent="true">
<ion-toolbar>
<ion-title>Blank</ion-title>
</ion-toolbar>
</ion-header>

<ion-content :fullscreen="true">
<ion-header collapse="condense">
<ion-toolbar>
<ion-title size="large">Blank</ion-title>
</ion-toolbar>
</ion-header>

<div id="container">
<strong>Ready to create an app?</strong>
<p>
Start with Ionic
<a target="_blank" rel="noopener noreferrer" href="https://ionic.nodejs.cn/components"
>UI Components</a
>
</p>
</div>
</ion-content>
</ion-page>
</template>

<script setup lang="ts">
import { IonContent, IonHeader, IonPage, IonTitle, IonToolbar } from '@ionic/vue';
</script>

<style scoped>
#container {
text-align: center;

position: absolute;
left: 0;
right: 0;
top: 50%;
transform: translateY(-50%);
}

#container strong {
font-size: 20px;
line-height: 26px;
}

#container p {
font-size: 16px;
line-height: 22px;

color: #8c8c8c;

margin: 0;
}

#container a {
text-decoration: none;
}
</style>

与我们开始使用的 App 组件非常相似,我们有一些针对特定 Ionic Framework 组件的导入、来自 Vue 的导入、Vue 组件以及与我们的组件一起使用的样式。

¥Much like the App component we started with, we have some imports for specific Ionic Framework components, an import from Vue, the Vue component, and styles to go along with our component.

对于我们的样式,请注意我们已将样式指定为 scoped。这意味着我们在这里编写的样式仅适用于该组件。这对于防止样式从组件中泄漏并影响应用的其他部分非常有用。我们强烈建议对 Ionic Vue 应用使用 scoped 样式。

¥For our styles, notice that we have specified our styles to be scoped. This means that the styles we write here will only apply to this component. This is useful for preventing styles from leaking out of a component and affecting other parts of your application. We strongly recommend using scoped styles for Ionic Vue applications.

IonPage 是所有页面的基础组件(具有路由/URL 的组件),并包括全屏组件的一些常见构建块,如标题、标题和内容组件。

¥IonPage is the base component for all pages (a component with a route/URL), and includes some common building blocks of a full-screen component, like header, title, and content components.

注意

创建你自己的页面时,不要忘记让 IonPage 作为它们的根组件。让 IonPage 成为根组件很重要,因为它有助于确保转换正常工作并提供 Ionic Framework 组件所依赖的基础 CSS。

¥When creating your own pages, do not forget to have IonPage be the root component for them. Having IonPage be the root component is important because it helps ensure transitions work properly as well as provides the base CSS the Ionic Framework components rely on.

IonHeader 是一个存在于页面顶部的组件。除了处理一些基于 Flexbox 的布局之外,它本身并没有做太多事情。它用于容纳组件,例如 IonToolbarIonSearchbar

¥IonHeader is a component meant to exist at the top of the page. It does not do much by itself, aside from handling some flexbox-based layout. It is meant to hold components, like IonToolbar or IonSearchbar.

IonContent,顾名思义,是我们页面的主要内容区域。它负责提供用户将与之交互的可滚动内容,以及可在应用中使用的任何滚动事件。

¥IonContent is, as its name suggests, the main content area for our page. It is responsible for providing a scrollable content that users will interact with, plus any scroll events that could be used in an app.

我们当前的内容相对简单,但不包含任何可以在真实应用中使用的内容,所以让我们改变一下。

¥Our current content is relatively simple, but does not contain anything that could be used in a real app, so let's change that.

注意

为了简洁起见,我们排除了组件的重复部分,例如来自其他组件的函数声明或导入语句。

¥For brevity, we are excluding repeating parts of our component, like the function declaration or import statements from other components.

<template>
<ion-page>
...
<ion-content>
<ion-list>
<ion-item>
<ion-checkbox label-placement="end" justify="start">
<h1>Create Idea</h1>
<ion-note>Run Idea By Brandy</ion-note>
</ion-checkbox>
<ion-badge color="success" slot="end">5 Days</ion-badge>
</ion-item>
</ion-list>
</ion-content>
</ion-page>
</template>

<script setup lang="ts">
import {
IonBadge,
IonCheckbox,
IonContent,
IonHeader,
IonItem,
IonList,
IonNote,
IonPage,
IonTitle,
IonToolbar,
} from '@ionic/vue';
</script>

IonContent 中,我们添加了 IonList 和更复杂的 IonItem 组件。让我们看看 IonItem,因为它是这里的核心。

¥Here in our IonContent, we are adding an IonList and a much more involved IonItem component. Let's look at IonItem as it is the centerpiece here.

<ion-item>
<ion-checkbox label-placement="end" justify="start">
<h1>Create Idea</h1>
<ion-note>Run Idea By Brandy</ion-note>
</ion-checkbox>
<ion-badge color="success" slot="end">5 Days</ion-badge>
</ion-item>

查看我们的代码,我们有一个名为 slot 的特殊属性。这是让 IonItem 知道渲染时将 IonBadge 放置在何处的关键。这不是 Vue API,而是 Web 标准 API,并且在许多 Ionic Framework 组件中使用。此外,这与你可能记得的 Vue 2 中的 slot API 不同。(有关插槽的更多信息,请参阅此处的 MDN 文档。)

¥Looking at our code, we have a special attribute called slot. This is key for letting the IonItem know where to place the IonBadge when it renders. This is not a Vue API, but a web standards API, and it is used across many Ionic Framework components. Additionally, this is different from the slots API you may recall from Vue 2. (For more information on slots, see the MDN docs here.)

让我们看看 Ionic Framework 中的另一个组件 FAB。浮动操作按钮是提供从应用的其余部分提升的主要操作的好方法。对于这个 FAB,我们需要三个组件:一个 FAB、一个 FAB 按钮和一个图标。

¥Let's look at another component from Ionic Framework, FAB. Floating Action Buttons are a nice way to provide a main action that is elevated from the rest of an app. For this FAB, we will need three components: a FAB, a FAB Button, and an Icon.

<template>
<ion-page>
<ion-content>
<ion-list> ... </ion-list>

<ion-fab vertical="bottom" horizontal="end" slot="fixed">
<ion-fab-button>
<ion-icon :icon="add"></ion-icon>
</ion-fab-button>
</ion-fab>
</ion-content>
</ion-page>
</template>

<script setup>
import {
IonBadge,
IonCheckbox,
IonContent,
IonFab,
IonFabButton,
IonHeader,
IonIcon,
IonItem,
IonList,
IonNote,
IonPage,
IonTitle,
IonToolbar,
} from '@ionic/vue';
import { add } from 'ionicons/icons';
</script>

在我们的主 IonFab 上,我们通过垂直和水平属性来设置它的定位。我们还使用 slot 属性将渲染位置设置为 "fixed"。这将告诉 IonFabIonContent 中的可滚动内容之外进行渲染。

¥On our main IonFab, we are setting its positioning with the vertical and horizontal attributes. We are also setting the render location to "fixed" with the slot attribute. This will tell IonFab to render outside of the scrollable content in IonContent.

现在让我们为此连接一个点击处理程序。单击 FAB 按钮时,我们想要导航到一个新页面(我们稍后将创建该页面)。为此,我们需要访问 Vue Router 的导航 API。这可以通过从 vue-router 包导入 useRouter 来完成。

¥Now let's wire up a click handler to this. When clicking the FAB button, we want to navigate to a new page (which we will create in a moment). To do this, we will need to get access to Vue Router's navigation API. This can be done by importing useRouter from the vue-router package.

<template>
<ion-page>
<ion-content>
<ion-list> ... </ion-list>

<ion-fab vertical="bottom" horizontal="end" slot="fixed">
<ion-fab-button @click="() => router.push('/new')">
<ion-icon :icon="add"></ion-icon>
</ion-fab-button>
</ion-fab>
</ion-content>
</ion-page>
</template>

<script setup>
import { add } from 'ionicons/icons';
import { useRouter } from 'vue-router';
const router = useRouter();
</script>

在我们的组件文件中,我们导入 useRouter 函数。调用时,此函数会将路由依赖注入到组件中。它使我们能够从 Vue Router 访问历史 API,从而允许我们将新路由推送到导航堆栈上。在我们的 IonFabButton 上,我们可以添加一个点击处理程序,只需调用 router.push 并传入新路由即可。在本例中,我们将导航至 new

¥In our component file, we are importing the useRouter function. When called, this function injects the router dependency into the component. It gives us access to the history API from Vue Router, allowing us to push a new route onto the navigation stack. On our IonFabButton, we can add a click handler, and just call router.push and pass in the new route. In this case, we will navigate to new.

<ion-fab-button @click="() => router.push('/new')"> ... </ion-fab-button>

创建新路由

¥Creating a new Route

现在我们已经有了在应用中导航的部件,我们需要创建一个新组件并将新路由添加到我们的路由声明中。让我们打开 router/index.ts 文件并添加新路由。

¥Now that we have the pieces in place to navigate in our app, we need to create a new component and add the new route to our router declaration. Let's open our router/index.ts file and add the new route.



import { createRouter, createWebHistory } from '@ionic/vue-router';


import { RouteRecordRaw } from 'vue-router';


import HomePage from '@/views/HomePage.vue';




import NewItem from '@/views/NewItem.vue';



const routes: Array<RouteRecordRaw> = [
{
path: '/',
redirect: '/home',
},
{
path: '/home',
name: 'Home',
component: HomePage,
},
{
path: '/new',
name: 'NewItem',
component: NewItem,
},
];

const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
});

export default router;

现在我们的路由有了路由 /new 的条目,我们将创建所需的组件 NewItem。这将存在于 views/NewItem.vue 中。

¥With our router now having an entry for the route /new, we will create the component needed, NewItem. This will exist in views/NewItem.vue.

现在让我们用一些占位符内容填充 NewItem.vue 文件。

¥Let's fill the NewItem.vue file with some placeholder content for the moment.

<template>
<ion-page>
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-back-button></ion-back-button>
</ion-buttons>
<ion-title>New Item</ion-title>
</ion-toolbar>
</ion-header>
<ion-content></ion-content>
</ion-page>
</template>

<script setup lang="ts">
import { IonBackButton, IonButtons, IonContent, IonHeader, IonPage, IonTitle, IonToolbar } from '@ionic/vue';
</script>
注意

每个视图必须包含 IonPage 组件。如果没有它,页面转换将无法正常工作。请参阅 IonPage 文档 了解更多信息。

¥Each view must contain an IonPage component. Page transitions will not work correctly without it. See the IonPage Documentation for more information.

这里的内容应该与 Home 组件类似。这里不同的是 IonBackButton 组件。这用于导航回之前的路由。看起来很容易,对吧?好的,但是如果我们重新加载页面怎么办?

¥The content here should look similar to the Home component. What is different here is the IonBackButton component. This is used to navigate back to the previous route. Seems easy enough, right? Ok, but what if we reload the page?

在这种情况下,内存中的历史记录将丢失,因此后退按钮消失。为了解决这个问题,我们可以将 default-href 属性值设置为没有历史记录时要导航到的 URL。

¥In this case, the in-memory history is lost, so the back button disappears. To address this, we can set the default-href attribute value to the URL we want to navigate to if there is no history.

<ion-back-button default-href="/home"></ion-back-button>

现在,如果不存在应用历史记录,我们将能够导航回我们的主页路由。

¥Now, If there is no app history present, we will be able to navigate back to our home route.

调用组件的方法

¥Calling Methods on Components

为了调用任何 Ionic Vue 组件上的方法,你首先需要获取对组件实例的引用。接下来,你需要使用 $el 访问底层 Web 组件并调用该方法。

¥In order to call a method on any of the Ionic Vue components, you will first need to get a reference to the component instance. Next, you will need to access the underlying Web Component using $el and call the method.

在其他框架集成(例如 Ionic React)中,不需要这样做,因为你提供的任何 ref 都会自动转发到底层 Web 组件实例。由于 Vue 管理引用方式的限制,我们无法在这里做同样的事情。

¥In other framework integrations such as Ionic React, this is not needed as any ref you provide is automatically forwarded to the underlying Web Component instance. We are unable to do the same thing here due to limitations in how Vue manages refs.

<template>
<ion-content ref="content">
<ion-button @click="scrollToBottom">Scroll to Bottom</ion-button>

...
</ion-content>
</template>

<script setup lang="ts">
import { IonButton, IonContent } from '@ionic/vue';
import { ref } from 'vue';

const content = ref();
const scrollToBottom = () => {
content.value.$el.scrollToBottom(300);
};
</script>

添加图标

¥Adding Icons

Ionic Vue 预装了 Ionic 图标。开发者可以通过多种方式在应用中使用它们。

¥Ionic Vue comes with Ionicons pre-installed. There are a couple options developers have for using them in their application.

每个组件导入

¥Per-Component Imports

每个组件导入是使用 Ionicons 的推荐方法。这涉及从 ionicons 包导入你选择的图标并将其传递到你的模板:

¥Per-Component Imports is the recommended approach to using Ionicons. This involves importing the icon of your choice from the ionicons package and passing it to your template:

<template>
<ion-page>
<ion-content>
<ion-icon :icon="heart"></ion-icon>
</ion-content>
</ion-page>
</template>

<script setup>
import { heart } from 'ionicons/icons';
import { IonContent, IonIcon, IonPage } from '@ionic/vue';
</script>

让我们分解一下我们在这里所做的事情。首先,我们从 ionicons/icons 导入 heart 图标。这将为我们的图标加载适当的 SVG 数据。

¥Let's break down what we are doing here. First, we are importing the heart icon from ionicons/icons. This will load the appropriate SVG data for our icon.

然后我们通过 icon 属性将图标数据传递到 ion-icon 组件中。

¥Then we pass the icon data into the ion-icon component via the icon property.

开发者还可以根据模式设置不同的图标:

¥Developers also have the option of setting different icons based upon the mode:

<template>
<ion-page>
<ion-content>
<ion-icon :ios="logoApple" :md="logoAndroid"></ion-icon>
</ion-content>
</ion-page>
</template>

<script setup>
import { logoAndroid, logoApple } from 'ionicons/icons';
import { IonContent, IonIcon, IonPage } from '@ionic/vue';
</script>

请注意,导入时任何带有连字符的图标名称都应采用驼峰式大小写。

¥Note that any icon names that are hyphenated should be written in camel case when importing.

全局导入

¥Global Imports

另一个选项是全局导入特定图标。通常不建议这样做,因为它会强制每次启动应用时加载图标,并且会增加应用的初始块大小。

¥The other option is to import specific icons globally. This is not typically recommended as it will force icons to be loaded every time your application starts and can increase your application's initial chunk size.

话虽如此,在某些情况下,全局加载特定图标是有意义的:

¥That being said, there may be use cases when it makes sense to load specific icons globally:

main.ts

import { addIcons } from 'ionicons';
import { heart } from 'ionicons/icons';

addIcons({
heart: heart,
});

HomePage.vue

<template>
<ion-page>
<ion-content>
<ion-icon icon="heart"></ion-icon>
</ion-content>
</ion-page>
</template>

<script setup>
import { IonContent, IonIcon, IonPage } from '@ionic/vue';
</script>

main.ts 中,addIcons 函数让我们可以全局注册图标,并给它一个字符串作为键。然后,我们在 Home 组件中通过该键引用该图标。

¥In main.ts, the addIcons function lets us register icons globally and give it a string as a key. We then reference the icon by that key in our Home component.

优化你的构建

¥Optimizing Your Build

Vue 为你提供了多种工具来微调你的应用。本节将介绍与 Ionic Framework 最相关的选项。

¥Vue gives you several tools to fine tune your application. This section will cover the options that are most relevant to Ionic Framework.

¥Local Component Registration (Recommended)

默认情况下,Ionic Framework 组件在本地注册。通过本地注册,这些组件将被导入并提供给你想要在其中使用它们的每个 Vue 组件。这是推荐的方法,因为它允许延迟加载和树摇动与 Ionic Framework 组件一起正常工作。

¥By default, Ionic Framework components are registered locally. With local registration, these components are imported and provided to each Vue component you want to use them in. This is the recommended approach as it allows lazy loading and treeshaking to work properly with Ionic Framework components.

这种方法的一个缺点是多次重新导入 Ionic Framework 组件可能很乏味。然而,我们认为你所获得的性能优势是值得的。

¥The one downside to this approach is that it may be tedious to re-import your Ionic Framework components multiple times. However, we feel that the performance benefits you receive in exchange are worth it.

另请注意,本地注册的组件在子组件中不可用。你将需要重新导入要在子组件中使用的 Ionic Framework 组件。

¥Also note that locally registered components are not available in subcomponents. You will need to re-import the Ionic Framework components you would like to use in your subcomponent.

我们来看看本地组件注册是如何工作的:

¥Let's take a look at how local component registration works:

<template>
<ion-page>
<ion-content>
<SubComponent></SubComponent>
</ion-content>
</ion-page>
</template>

<script setup lang="ts">
import { IonContent, IonPage } from '@ionic/vue';
import SubComponent from '@/components/SubComponent.vue';
</script>

在上面的示例中,我们使用 IonPageIonContent 组件。为了使用它们,我们从 @ionic/vue 导入它们。从那里,我们可以使用模板中的组件。

¥In the example above, we are using the IonPage and IonContent components. To use them, we import them from @ionic/vue. From there, we can use the components in our template.

请注意,由于我们在本地注册这些组件,因此 IonPageIonContentSubComponent 中均不可用,除非我们也在那里注册它们。

¥Note that since we are registering these components locally, neither IonPage nor IonContent will be available in SubComponent unless we register them there as well.

有关详细信息,请参阅 本地注册 Vue 文档

¥For more information, see the Local Registration Vue Documentation.

全局组件注册

¥Global Component Registration

注册组件的另一个选项是使用全局注册。全局注册涉及导入你想要在 main.ts 中使用的组件并在 Vue 应用实例上调用 component 方法。

¥The other option for registering components is to use global registration. Global registration involves importing the components you want to use in main.ts and calling the component method on your Vue app instance.

虽然这使得将 Ionic Framework 组件添加到 Vue 应用变得更容易,但全局注册通常并不理想。引用 Vue 文档:“如果你使用像 Webpack 这样的构建系统,全局注册所有组件意味着即使你停止使用某个组件,它仍然可以包含在你的最终构建中。这不必要地增加了用户必须下载的 JavaScript 量”。

¥While this makes it easier to add Ionic Framework components to your Vue app, global registration often is not ideal. To quote the Vue documentation: "If you're using a build system like Webpack, globally registering all components means that even if you stop using a component, it could still be included in your final build. This unnecessarily increases the amount of JavaScript your users have to download".

我们来看看全局组件注册是如何工作的:

¥Let's take a look at how global component registration works:

main.ts



import { IonContent, IonicVue, IonPage } from '@ionic/vue';



const app = createApp(App).use(IonicVue).use(router);

app.component('ion-content', IonContent);
app.component('ion-page', IonPage);

MyComponent.vue

<template>
<ion-page>
<ion-content>
<SubComponent></SubComponent>
</ion-content>
</ion-page>
</template>

<script setup lang="ts">
import SubComponent from '@/components/SubComponent.vue';
</script>

在上面的示例中,我们使用 IonPageIonContent 组件。要使用它们,我们首先从 @ionic/vue 导入 main.ts。从那里,我们在应用实例上调用 component 方法,并向其传递标签名称和组件定义。完成此操作后,我们可以在应用的其余部分中使用这些组件,而无需将它们导入到每个 Vue 组件中。

¥In the example above, we are using the IonPage and IonContent components. To use them, we first import them from @ionic/vue in main.ts. From there, we call the component method on our app instance and pass it the tag name as well as the component definition. After we do that, we can use the components in the rest of our application without having to import them into each Vue component.

有关详细信息,请参阅 全局注册 Vue 文档

¥For more information, see the Global Registration Vue Documentation.

预取应用 JavaScript

¥Prefetching Application JavaScript

默认情况下,Vue CLI 会自动为应用中的 JavaScript 生成预取提示。预取利用浏览器空闲时间来下载用户在不久的将来可能访问的文档。当用户访问需要预取文档的页面时,可以从浏览器的缓存中快速提供该文档。

¥By default, the Vue CLI will automatically generate prefetch hints for the JavaScript in your application. Prefetching utilizes the browser idle time to download documents that the user might visit in the near future. When the user visits a page that requires the prefetched document, it can be served quickly from the browser's cache.

预取会消耗带宽,因此如果你有大型应用,你可能需要禁用它。你可以通过修改或创建 vue.config.js 文件来完成此操作:

¥Prefetching consumes bandwidth, so if you have a large app, you may want to disable it. You can do this by modifying or creating your vue.config.js file:

vue.config.js

module.exports = {
chainWebpack: (config) => {
config.plugins.delete('prefetch');
},
};

上面的配置将阻止预取所有文件,而是在需要时加载它们。你还可以选择某些块进行预取。查看 有关预取的 Vue CLI 文档 了解更多示例。

¥The configuration above will prevent all files from being prefetched and, instead, will be loaded when they are needed. You can also select certain chunks to prefetch. Check out the Vue CLI Docs on Prefetching for more examples.

构建原生应用

¥Build a Native App

我们现在已经掌握了 Ionic Vue 应用的基础知识,包括一些 UI 组件和导航。Ionic Framework 组件的很棒之处在于它们可以在任何地方工作,包括 iOS、Android 和 PWA。为了部署到移动设备及其他设备,我们使用 Ionic 的跨平台应用运行时 Capacitor。它提供了一组一致的、以 Web 为中心的 API,使应用能够尽可能接近 Web 标准,同时在支持它们的平台上访问丰富的原生设备功能。

¥We now have the basics of an Ionic Vue app down, including some UI components and navigation. The great thing about Ionic Framework’s components is that they work anywhere, including iOS, Android, and PWAs. To deploy to mobile and beyond, we use Ionic’s cross-platform app runtime Capacitor. It provides a consistent, web-focused set of APIs that enable an app to stay as close to web-standards as possible while accessing rich native device features on platforms that support them.

添加原生功能很容易。首先,将 Capacitor 添加到你的项目中:

¥Adding native functionality is easy. First, add Capacitor to your project:

ionic integrations enable capacitor

接下来,构建项目,然后添加你选择的平台:

¥Next, build the project, then add your platform of choice:

ionic build
ionic cap add ios
ionic cap add android

我们使用标准的原生 IDE(Xcode 和 Android Studio)来打开、构建和运行 iOS 和 Android 项目:

¥We use the standard native IDEs (Xcode and Android Studio) to open, build, and run the iOS and Android projects:

ionic cap open ios
ionic cap open android

其他详细信息可参见 此处

¥Additional details can be found here.

接下来,查看可用的 所有 API。有一些很棒的功能,包括 相机接口。我们只需几行代码就可以实现照片拍摄功能:

¥Next, check out all the APIs that are available. There is some great features, including the Camera API. We can implement photo capture functionality in just a few lines of code:

<template>
<ion-page>
<ion-header>
<ion-toolbar>
<ion-title>Ionic Blank</ion-title>
</ion-toolbar>
</ion-header>
<ion-content class="ion-padding">
<img :src="imageSrc" />
<ion-button @click="takePhoto()">Take Photo</ion-button>
</ion-content>
</ion-page>
</template>

<script setup lang="ts">
import { IonButton, IonContent, IonHeader, IonPage, IonTitle } from '@ionic/vue';
import { ref } from 'vue';
import { Camera, CameraResultType } from '@capacitor/camera';

const imageSrc = ref('');
const takePhoto = async () => {
const image = await Camera.getPhoto({
quality: 90,
allowEditing: true,
resultType: CameraResultType.Uri,
});

imageSrc.value = image.webPath;
};
</script>

从这往哪儿走

¥Where to go from here

本指南涵盖了创建 Ionic Vue 应用的基础知识、添加一些基本导航以及介绍 Capacitor 作为构建原生应用的一种方式。要更深入地了解如何使用 Vue 和 Capacitor 构建完整的 Ionic Framework 应用,请关注我们的 第一个应用指南

¥This guide covered the basics of creating an Ionic Vue app, adding some basic navigation, and introducing Capacitor as a way of building native apps. To dive deeper into building complete Ionic Framework apps with Vue and Capacitor, follow our First App guide.

要更详细地了解 Ionic Frameworks 的组件,请查看 组件 API 页面。有关 Vue 的更多详细信息,请查看 Vue 文档。要继续构建原生功能,请参阅 Capacitor 文档

¥For a more detailed look at Ionic Frameworks’s components, check out the component API pages. For more details on Vue, review the Vue Docs. To keep building native features, see the Capacitor docs.

快乐的应用构建!🎉

¥Happy app building! 🎉