Skip to main content

A Getting Started Sample On Ionic5 Application Using Vue

In this article, we are going to understand the steps for installing and creating the Ionic5 sample application using Vue and also run our sample on the android mobile device emulator.

Create A Sample App Of Ionic5 Using Vue :

To begin to create an Ionic application, we should have the Ionic CLI installed in our system environment.
Command to install latest Ionic CLI:
npm install -g @ionic/cli@latest
Now run the following command to create Ionic5 using the Vue application.
Command to create Ionic Vue application
ionic start your_app_name blank --type vue
By default Ionic provides few templated projects here I'm creating the 'blank' project.

TypeScript Or Javascript:

By default Ionic sample created with the support of TypeScript in any library like angular, react, and vue. Typescript can be chosen to develop our application. But in the case of Vue most of the developers or preferred to choose javascript syntax instead of Typescript for application development. So to make our Ionic Vue application use javascript we need to remove few Typescript references, so follow the below steps.
  • Remove TypeScript dependencies.
command to unistall the typescript dependencies
npm uninstall --save typescript @types/jest @typescript-eslint/eslint-plugin @typescript-eslint/parser @vue/cli-plugin-typescript @vue/eslint-config-typescript
  • We need to change the file extensions from ".ts" to ".js", we mostly have 2 '.ts files' like 'main.ts' and 'router/index.ts'.
  • In the '.eslintrc.js' file needs to remove the '@vue/typescript/recommended' from the 'extends' array property and next need to remove the @typescript-eslint/no-explicit-any': 'off' property from the rules object.
  • Now remove the 'Array<RouteRecordRaw>' type in 'router/index.js'.
  • Delete the 'shims-vue.d.ts' file.
  • Remove the 'lang="ts"' attribute on script tag in our '.vue' files like 'App.vue' and 'view/Home.vue'.

Create Pages Vue Components:

Before creating our page vue components let's restructure our project template like:
  • Delete the 'views/Home.vue' file and 'views' folder.
  • Remove the 'Home.vue' component route and its references from the 'router/index.js' file.
Now let's create 2 view page components in our sample application like 'Home.vue' and 'Todos.vue'.
src/pages/Home.vue:
<template>
    <div>
        <h3>Welcome To Demo On Ionic5 with Vue</h3>
    </div>
</template>
<script>
export default {
    
}
</script>
src/pages/Todos.vue:
<template>
    <div>
        Todo's List
    </div>
</template>
<script>
export default {
    
}
</script>
Now configure the routes for our newly created page components
src/router/index.js:
import { createRouter, createWebHistory } from "@ionic/vue-router";

import Home from "../pages/Home.vue";
import Todos from "../pages/Todos.vue";

const routes = [
  {
    path: "/",
    redirect: "/home",
  },
  {
    path: "/home",
    component: Home,
  },
  {
    path: "/todos",
    component: Todos,
  },
];

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

export default router;
Command to run the application
ionic serve

Add Master Layout Vue Component:

Till now our sample application doesn't have any layout like header, footer, etc. Now we have to define a master template for our application which will be applied for all the pages. The core ionic components to define the layout vue component are like:
  • IonPage
  • IonHeader
  • IonContent
  • IonTitle
  • IonToolbar
Let's create a master layout for our sample application.
src/components/MainLayout.vue:
<template>
    <ion-page>
        <ion-header>
            <ion-toolbar>
                <ion-title>{{pageTitle}}</ion-title>
            </ion-toolbar>
        </ion-header>
        <ion-content>
            <slot></slot>
        </ion-content>
    </ion-page>
</template>
<script>
import { IonPage, IonHeader, IonContent, IonTitle, IonToolbar } from '@ionic/vue';
export default {
    components:{
        IonPage,
        IonHeader,
        IonContent,
        IonTitle,
        IonToolbar
    },
    props:['pageTitle']
}
</script>
  • Here we have defined our master template using the Ionic core components. 
  • The '<slot>' tag is the area in which our routed page content will be rendered. 
  • The page title of each page will be passed dynamically using the input properties using the 'props'.
Now register our 'MasterLayout.vue' component globally in the main.js file.
src/main.js:
import MainLayout from  './components/MainLayout.vue';
// code hidden for display purpose

app.component('main-layout',MainLayout);
Now update our page components to use the layout components.
src/pages/Home.vue:(Html Part)
<template>
    <main-layout pageTitle="Home">
        <h4>WelCome To Demo On Ionic5 with Vue</h4>
    </main-layout>
</template>
  • Here we have defined everything inside of the layout component and also passing the 'pageTitle' input parameter
src/pages/Todos.vue:(Html Part)
<template>
    <main-layout pageTitle="Todos">
        <h4>Todos List</h4>
    </main-layout>
</template>

Add Styling:

HTML has the ability to add the styles based on the tags as well similarly in ionic also we add the styles based on the Ionic component element tag. But to add styles to the ionic component element tag we need to follow the original documentation from the ionic because we can only add style by overriding the configuration provided by the Ionic, so we need to check only those style configurations of each Ionic component.

So in this sample, I'm going to add some styles to my 'IonToolbar' component. so let's create styles file for our MasterLayout component.
src/theme/layout.css:
ion-toolbar{
    --background: var(--ion-color-primary);
    --color: var(--ion-color-primary-contrast);
}
  • Here we can observe that trying to add styles to IonToolbar. Here also observe the style configurations like '--background' and '--color' provided by IonToolbar component. The value are we assigned are CSS variables that load from the 'src/theme/variable.css' file.
Now import our layout.css file into the main.js
src/main.js:
import './theme/layout.css';

Add Menu:

To our application, we are going to add a side menu using the 'IonMenu' component. so let's create our menu and its items as a separate component.
src/components/SideMenu.vue:(Html Part)
<template>
  <ion-menu side="start" menu-id="sidemenu" content-id="mymenu">
    <ion-header>
      <ion-toolbar>
        <ion-title> WelCome! </ion-title>
      </ion-toolbar>
    </ion-header>
    <ion-content>
      <ion-list>
        <ion-item button @click="toPage('/home')">
          <ion-icon :icon="home" slot="start"></ion-icon>
          <ion-label>Home</ion-label>
        </ion-item>
        <ion-item button @click="toPage('/todos')">
          <ion-icon :icon="build" slot="start"></ion-icon>
          <ion-label>Todos</ion-label>
        </ion-item>
      </ion-list>
    </ion-content>
  </ion-menu>
</template>
  • Here we render the 'ion-menu' component as the root component. Similar to the 'ion-page' component our 'ion-menu' component also have child components like 'ion-header' and 'ion-content'. 
  • (Line: 2) Our 'ion-menu' component has the attribute 'menu-id' which defines the name of the menu, we can have n-number of menus in our application that can be determined by using the 'menu-id' attribute value. We used another attribute like 'content-id' that explains on which area of the content this menu should reflect mostly its value should be matched with 'id' value of the 'ion-router-outlet' in App.vue file
  • (Line: 10&14) For our 'ion-item' components, we registered click with a callback method and path to be navigated as the input value to the method. We also decorated the 'button' directive this gives nice click transition animation for our menu items.
  • (Line: 11&15) For our 'ion-icon' we added the data values like 'home' & 'build' which loads from 'ionicons/icons'.
src/components/SideMenu.vue:(Script Part):
<script>
import {IonMenu,IonHeader,IonContent,IonToolbar,IonTitle,
  IonList,IonItem,IonIcon,IonLabel,menuController,} from "@ionic/vue";
import { home, build,  } from "ionicons/icons";
import {useRouter} from 'vue-router'
export default {
  components: {
    IonMenu,
    IonHeader,
    IonContent,
    IonToolbar,
    IonTitle,
    IonList,
    IonItem,
    IonIcon,
    IonLabel,
  },
  data() {
    return {
      home,
      build
    };
  },
  setup(){
    const router = useRouter();
    return{
      router
    };
  },
  methods:{
    toPage(path){
      menuController.close('sidemenu');
      this.router.push(path);
    }
  }
};
</script>
  • (Line:4) Icon values are loaded from 'ionicons/icons'.
  • (Line: 18-23) Icon values are returned as data values.
  • (Line: 24-29) Using vue composition API creating the route instance.
  • The 'menuController' can access any 'ion-menu' that we have created in our application. Here we are closing the menu on selecting items in it to navigate to the new page.
Now we need to add a button and icon for the menu in our MainLayout.vue file for opening the menu.
src/components/MainLayout.vue:(Html Part)
<template>
  <ion-page>
    <ion-header>
      <ion-toolbar>
        <ion-buttons @click="openMenu()" slot="start">
          <ion-icon :icon="menu" slot="start"></ion-icon>
        </ion-buttons>
        <ion-title>{{ pageTitle }}</ion-title>
      </ion-toolbar>
    </ion-header>
    <ion-content>
      <slot></slot>
    </ion-content>
  </ion-page>
</template>
  • (Line: 5-7) Add a 'ion-buttons' for invoking the menu.
src/components/MainLayout.vue:(Script Part)
<script>
import {
  IonPage,IonHeader,IonContent,IonTitle,IonToolbar,
  IonButtons,menuController,IonIcon,} from "@ionic/vue";
import { menu } from "ionicons/icons";
export default {
  components: {
    IonPage,
    IonHeader,
    IonContent,
    IonTitle,
    IonToolbar,
    IonButtons,
    IonIcon,
  },
  props: ["pageTitle"],
  data() {
    return {
      menu,
    };
  },
  methods: {
    openMenu() {
      menuController.open("sidemenu");
    },
  },
};
</script>
  • (Line: 24) Using the 'menuController' we are opening the menu by passing the value of the 'menu-id'(in SideMenu.vue file).
Now render our 'side-menu' component in the 'App.vue' file.
src/App.vue:(Html Part)
<template>
  <ion-app>
    <side-menu></side-menu>
    <ion-router-outlet id="mymenu" />
  </ion-app>
</template>
  • (Line: 3)  Rendered our 'side-menu' component.
  • (Line: 4) We added id for the 'ion-router-outlet' this value need to given for 'content-id' of the 'ion-menu' in the 'SideMenu.vue' file.

API Call:

Now in our 'Todo.vue' component, we are going to consume API to display the collection of todo items.

Here we will use frees test todos API like "https://jsonplaceholder.typicode.com/todos"

To consume API calls from the vue component we need to install the 'axios' library.
Command to install axios library
npm install axios
Now update our 'Todos.vue' to fetch the data from our test API.
src/pages/Todos.vue:(Html Part)
<template>
    <main-layout pageTitle="Todos">
        <h4>Todos List</h4>
        <ion-button expand="full" @click="showtodos()">show Todos</ion-button>
        <ion-list >
            <ion-item v-for="todo in myTodos" :key="todo.id" >{{todo.title}}</ion-item>
        </ion-list>
    </main-layout>
</template>
  • Here on clicking the 'Show Todos' button, we are going to invoke the API and then results will be looped through our 'ion-item' component.
src/pages/Todos.vue:(Script Part)
<script>
import {IonButton, IonList, IonItem} from '@ionic/vue';
import axios from 'axios';
export default {
    components:{
        IonButton,
        IonList,
        IonItem
    },
    data(){
        return {
            myTodos:[]
        }
    },
    methods:{
        async showtodos(){
           const response = await axios.get("https://jsonplaceholder.typicode.com/todos");
           this.myTodos = response.data;
        }
    }
}
</script>

Test In Android Mobile Emulator:

So to test in android mobile emulator please make sure to install the android studio on your system.

Now to run our application as an android app we need to use the support of the 'Capacitor'. The Capacitor is a cross-platform native runtime that makes it easy to build modern web apps that run natively on ios, android, and the web.

By creating an application using the Ionic framework 'capacitor' will be added automatically for all the latest applications. So to check that apps are having capacitors installed run the below command.
command to generate capacitor
ionic integrations enable capacitor
Now we need to initialize the capacitor with app information like application name and application id these values are very important to publish the app.
command to create app name and id with capacitor
npx cap init [appName] [appId]
Running command successfully our app info will be added into the capacitor.cofig.json file.
Nex runs the command to generate the android supportive files.
command to generate android files
npx cap add android
On running command if you face the following error

This error occurs because till now we haven't built our project to generate the android files. so to overcome these issues on run command like 'npm run build' and next try again our command like 'npx cap add android'.

After the success of  'npx cap add android' run the following command to open our project in android studio where we can run app on mobile emulator
command to open our code in android studio
npx cap open android
Now before running our application we need to set up an emulator if we don't have one. So to setup emulator in android studio select the 'Tools' menu inside of it a select option like 'AVD Manager' and then create your emulator.

Now in the android studio select your emulator and run the application which opens our ionic app in the emulator.



Support Me!
Buy Me A Coffee PayPal Me

Wrapping Up:

Hopefully, I think this article delivered some useful information on creating a sample Ionic5 Vue application. I love to have your feedback, suggestions, and better techniques in the comment section below.

Refer:

Follow Me:

Comments

  1. Excellent !!!

    One cut/paste typo:

    Now import our layout.css file into the main.js
    src/main.js:
    import './theme/variables.css';

    should be: import './theme/layout.css';

    ReplyDelete

Post a Comment

Popular posts from this blog

.NET6 Web API CRUD Operation With Entity Framework Core

In this article, we are going to do a small demo on AspNetCore 6 Web API CRUD operations. What Is Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains a programming function that can be requested via HTTP calls to save or fetch the data for their respective clients. Some of the key characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build REST full services. Create A .NET6 Web API Application: Let's create a .Net6 Web API sample application to accomplish our

A Small Guide On NestJS Queues

NestJS Application Queues helps to deal with application scaling and performance challenges. When To Use Queues?: API request that mostly involves in time taking operations like CPU bound operation, doing them synchronously which will result in thread blocking. So to avoid these issues, it is an appropriate way to make the CPU-bound operation separate background job.  In nestjs one of the best solutions for these kinds of tasks is to implement the Queues. For queueing mechanism in the nestjs application most recommended library is '@nestjs/bull'(Bull is nodejs queue library). The 'Bull' depends on Redis cache for data storage like a job. So in this queueing technique, we will create services like 'Producer' and 'Consumer'. The 'Producer' is used to push our jobs into the Redis stores. The consumer will read those jobs(eg: CPU Bound Operations) and process them. So by using this queues technique user requests processed very fastly because actually

Part-1 Angular JWT Authentication Using HTTP Only Cookie[Angular V13]

In this article, we are going to implement a sample angular application authentication using HTTP only cookie that contains a JWT token. HTTP Only JWT Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-Only cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use authentication with HTTP only JWT cookie then we no need to implement custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To implement JWT cookie authentication we need to set up an API. For that, I had created a mock authentication API(Using the NestJS Se

Usage Of CancellationToken In Asp.Net Core Applications

When To Use CancellationToken?: In a web application request abortion or orphan, requests are quite common. On users disconnected by network interruption or navigating between multiple pages before proper response or closing of the browser, tabs make the request aborted or orphan. An orphan request can't deliver a response to the client, but it will execute all steps(like database calls, HTTP calls, etc) at the server. Complete execution of an orphan request at the server might not be a problem generally if at all requests need to work on time taking a job at the server in those cases might be nice to terminate the execution immediately. So CancellationToken can be used to terminate a request execution at the server immediately once the request is aborted or orphan. Here we are going to see some sample code snippets about implementing a CancellationToken for Entity FrameworkCore, Dapper ORM, and HttpClient calls in Asp.NetCore MVC application. Note: The sample codes I will show in

Unit Testing Asp.NetCore Web API Using xUnit[.NET6]

In this article, we are going to write test cases to an Asp.NetCore Web API(.NET6) application using the xUnit. xUnit For .NET: The xUnit for .Net is a free, open-source, community-focused unit testing tool for .NET applications. By default .Net also provides a xUnit project template to implement test cases. Unit test cases build upon the 'AAA' formula that means 'Arrange', 'Act' and 'Assert' Arrange - Declaring variables, objects, instantiating mocks, etc. Act - Calling or invoking the method that needs to be tested. Assert - The assert ensures that code behaves as expected means yielding expected output. Create An API And Unit Test Projects: Let's create a .Net6 Web API and xUnit sample applications to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. Create a fo

Blazor WebAssembly Custom Authentication From Scratch

In this article, we are going to explore and implement custom authentication from the scratch. In this sample, we will use JWT authentication for user authentication. Main Building Blocks Of Blazor WebAssembly Authentication: The core concepts of blazor webassembly authentication are: AuthenticationStateProvider Service AuthorizeView Component Task<AuthenticationState> Cascading Property CascadingAuthenticationState Component AuthorizeRouteView Component AuthenticationStateProvider Service - this provider holds the authentication information about the login user. The 'GetAuthenticationStateAsync()' method in the Authentication state provider returns user AuthenticationState. The 'NotifyAuthenticationStateChaged()' to notify the latest user information within the components which using this AuthenticationStateProvider. AuthorizeView Component - displays different content depending on the user authorization state. This component uses the AuthenticationStateProvider

Angular 14 Reactive Forms Example

In this article, we will explore the Angular(14) reactive forms with an example. Reactive Forms: Angular reactive forms support model-driven techniques to handle the form's input values. The reactive forms state is immutable, any form filed change creates a new state for the form. Reactive forms are built around observable streams, where form inputs and values are provided as streams of input values, which can be accessed synchronously. Some key notations that involve in reactive forms are like: FormControl - each input element in the form is 'FormControl'. The 'FormControl' tracks the value and validation status of form fields. FormGroup - Track the value and validate the state of the group of 'FormControl'. FormBuilder - Angular service which can be used to create the 'FormGroup' or FormControl instance quickly. Form Array - That can hold infinite form control, this helps to create dynamic forms. Create An Angular(14) Application: Let'

How Response Caching Works In Asp.Net Core

What Is Response Caching?: Response Caching means storing of response output and using stored response until it's under it's the expiration time. Response Caching approach cuts down some requests to the server and also reduces some workload on the server. Response Caching Headers: Response Caching carried out by the few Http based headers information between client and server. Main Response Caching Headers are like below Cache-Control Pragma Vary Cache-Control Header: Cache-Control header is the main header type for the response caching. Cache-Control will be decorated with the following directives. public - this directive indicates any cache may store the response. private - this directive allows to store response with respect to a single user and can't be stored with shared cache stores. max-age - this directive represents a time to hold a response in the cache. no-cache - this directive represents no storing of response and always fetch the fr

Different HttpClient Techniques To Consume API Calls In Minimal API[.NET6]

In this article, we are going to implement different HttpClient techniques to consume API calls in minimal API. The different HttpClient techniques that we are going to explore are like: Register HttpClient Object Explicitly In DI(Dependency Injection Service) Named Client Type Client HttpRequestMessage Object Create A .NET6 Minimal API Project: Let's create a .Net6 Minimal API sample project to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. CLI command For Minimal API Project dotnet new webapi -minimal -o Your_Project_Name Create A Third Party API Response Model: Here I'm going to use a free third-party rest API that is "https://jsonplaceholder.typicode.com/posts". So to receive the response let's create a response model like 'Post.cs'. Program.cs:(Add Post.cs c

.Net5 Web API Managing Files Using Azure Blob Storage

In this article, we are going to understand the different file operations like uploading, reading, downloading, and deleting in .Net5 Web API application using Azure Blob Storage. Azure Blob Storage: Azure blob storage is Microsoft cloud storage. Blob storage can store a massive amount of file data as unstructured data. The unstructured data means not belong to any specific type, which means text or binary data. So something like images or pdf or videos to store in the cloud, then the most recommended is to use the blob store. The key component to creating azure blob storage resource: Storage Account:- A Storage account gives a unique namespace in Azure for all the data we will save. Every object that we store in Azure Storage has an address. The address is nothing but the unique name of our Storage Account name. The combination of the account name and the Azure Storage blob endpoint forms the base address for each object in our Storage account. For example, if our Storage Account is n