SlideShare a Scribd company logo
How to Build To-
do App using
Vue
Composition API
and Vuex 4 with
Typescript
www.bacancytechnology.com
Quick Summary:
Vue Composition API- Organized, Readable,
and Understandable
Introduction
In this tutorial, we will learn and explore
Vue Composition API. You might have
heard about it, but if not then don’t worry
at all! We will start from the basics. For
knowing Vue Composition API in a better
way you must have knowledge about
Options API, we will discuss that too!
I would suggest you visit my previous blog
of the Vue 3 Tutorial series- How to Build
To-do App with Vue 3 Typescript for setting
up the basic demo project because in this
tutorial we will be using the same github
repository.
What is Vue
Composition
API?
Ineffective patterns for reusing logic and
component
Poor readability when component grows
larger
Code gets complex and difficult to
manage when the project size increases
Creates confusion and makes it difficult
to use Typescript with ‘this
Vue Composition API is function-based APIs
that provides flexibility, improves code
readability, and helps to maintain
component logic. The main reason for
introducing Vue Composition API was to
address the limitations of Options API as the
component gets larger.
Here are some of the limitations associated
with Options API-
Vue
Composition
API vs
Options API
You might have seen this image if you are
learning Vue Composition API. Let’s see
briefly what does it mean.
The difference in the component because of
Vue Composition API
You will notice a setup() function is the
major change. It comprises the component’s
logic. In Options API we used to define data,
methods, lifecycle, etc separately as a
component option, but due to composition
API, setup() function will consist of all these.
You might not understand the impact of
this update until your component size
grows larger. If you worked with a large
project having complex component code or
have to understand other developers’ code,
you might understand the significance of
code understandability and readability
Vue Composition API sorts the component
code and makes the logic reusable in a much
better way
Let’s take a sample code from the Github
repository: Vue 3 Typescript, which we have
built in the previous blog- How to Build a
To-do App with Typescript: Vue 3 Tutorial.
The One with
Composition API
export default defineComponent({
name: "Home",
setup() {
const tasks = ref([]); // ref is used to make
the parameter reactive
const store = useStore(); //alternative to
Vue prototype of this.$store
tasks.value = store.state.tasks;
//this is the way to write methods
const setTaskComplete = (task: Task): void
=> {
store.commit(MutationType.CompleteTask,
task);
};
const deleteTask = (task: Task) => {
store.commit(MutationType.DeleteTask,
task);
};
// To support two-way data binding
return {
tasks,
setTaskComplete,
deleteTask
};
}
});
</script>
On the contrary, you can see that the
setup() function has combined all the six
components together, which increases the
readability and understandability of the
code.
Steps: How to
Build To-do
App using Vue
Composition
API and Vuex
4 with
Typescript.
Visit Vue 3 Tutorial with Typescript
blog to create the vue-typescript project
from scratch or click here to clone the
vue-typescript-demo.
For implementing Vue Composition API
with Typescript follow the below steps.
1. Integrating Vuex 4
In the previous, files were written in
Javascript with partial Typescript, but here
we will update all the files with pure
Typescript.
For integrating Vuex 4 with Typescript, we
will need to update two files:
store/index.js and store/mutations.js.
store/index.js
Open store/index.js and update the file
with the following code.
import Task from "@/models/Task";
import { createStore, Store as VuexStore,
CommitOptions } from "vuex";
import { Mutations, mutations } from
"./mutations";
export const store = createStore({
state: {
tasks: [
{
name: "Demo for VueJS and TS",
createdAt: new Date(),
updatedAt: new Date(),
completed: false,
},
},
] as Task[],
},
mutations,
actions: {},
modules: {},
});
//to make the store globally accessible
export function useStore() {
return store as Store;
}
export type Store = Omit<VuexStore<any>,
"commit"> & {
commit<K extends keyof Mutations, P
extends Parameters<Mutations[K]>[1]>(
key: K,
payload: P,
options?: CommitOptions
): ReturnType<Mutations[K]>;
};
Use the createStore() method to create
Vuex store.
For using the store in different
components export the useStore
function. Thus, the complete store is
accessible across our entire application.
For accessing the store in the
component, we need to inject it into the
app. Thankfully, the Vue-CLI had
already imported the entire store and
passed it within the Vue instance of our
application.
Explanation
Moving towards mutations.
store/mutation.ts
Mutations are methods used for
modifying the store state.
Mutations accept the state as its first
argument and payload as the second and
then updates the state with the received
payload.
As per the recommendation by Vuex
official doc, we will use constants for the
mutation types.
Open store/mutation.ts file and update it
with the following code below.
import { MutationTree } from "vuex";
import { findIndex } from "lodash";
export enum MutationType {
SetTask = "SET_TASKS",
CompleteTask = "COMPLETE_TASK",
DeleteTask = "REMOVE_TASK"
}
export type Mutations = {
[MutationType.SetTask](state: any, task:
any): void;
[MutationType.CompleteTask](state: any,
task: any): void;
[MutationType.DeleteTask](state: any, task:
any): void;
};
export const mutations:
MutationTree<any> & Mutations = {
[MutationType.SetTask](state, task) {
state.tasks.push(task);
},
[MutationType.DeleteTask](state, task) {
let taskIndex = findIndex(state.tasks,
task);
state.tasks.splice(taskIndex, ++taskIndex);
},
[MutationType.CompleteTask](state: any,
task: any) {
const taskIndex = findIndex(state.tasks,
task);
state.tasks[taskIndex].completed = true;
}
};
Vuex package provides a generic type-
MutationTree. It is used for declaring
the type of mutation tree.
MutationTypes enum stores all the
possible names of mutations.
Further, declaring a contract (types)
for every MutationType. Create a
variable named mutations for storing
all the implemented mutations. The
MutationTree < State > & Mutations
ensures that the type is implemented
correctly for avoiding Typescript
errors.
Explanation
2. Components using
Composition API
Implementing component API in the files –
AddTask.vue and Home.vue. For that, you
need to modify the code within < script > <
script / >
AddTask.vue
<script lang="ts">
import { defineComponent, ref } from "vue";
import Task from "@/models/Task";
import { useStore } from "@/store";
import { MutationType } from
"@/store/mutations";
import { useRouter } from "vue-router";
export default defineComponent({
name: "AddTask",
setup() {
const taskName = ref("");
const router = useRouter(); // Substitute of
Vue prototype this.$router
const store = useStore();
const addTask = (): void => {
const newTask = new
Task(taskName.value);
store.commit(MutationType.SetTask,
newTask);
taskName.value = "";
router.push({ path: "/" });
};
return { taskName, addTask };
}
});
</script>
As the name suggests, it is used for
adding new tasks to the to-do list.
Whenever the user clicks the button Add
Task, the addTask function commits the
SetTask mutation which will add the
newly added task to the existing tasks
list.
Once done, the UI is updated.
What’s happening in this component?
Home.vue
<script lang="ts">
import { defineComponent, ref } from "vue";
import Task from "@/models/Task";
import { useStore } from "@/store";
import { MutationType } from
"@/store/mutations";
export default defineComponent({
name: "Home",
setup() {
const tasks = ref([]);
const store = useStore();
tasks.value = store.state.tasks;
const setTaskComplete = (task: Task): void
=> {
store.commit(MutationType.CompleteTask
, task);
};
const deleteTask = (task: Task) => {
store.commit(MutationType.DeleteTask,
task);
};
</script>
return {
tasks,
setTaskComplete,
deleteTask
};
}
});
The component is responsible for
displaying and updating (marking it done
or deleting it) the to-do list.
Whenever the user clicks the tick button,
MutationType CompleteTask is triggered
with an argument task, for marking the
task as done.
Whenever the user clicks the tick button,
MutationType DeleteTask is triggered
with an argument task, for deleting the
task as done.
Once done, the UI is updated.
What’s happening in this component?
Takeaway
●Integrate Vuex 4 with Typescript
●Implement Vue Composition API with
Typescript
●Source code- Github Repository
We have mostly used the major feature
releases of Vuex 4 and integrated it with the
Composition API in Vue 3 to develop a small
demo app. With the practical
implementation, we have explored the
theoretical side of Composition API and seen
how it is different than Options API.
I hope you’ve learned a great deal from
the tutorial. If you have any suggestions
or questions please feel free to comment
below.
Visit the VueJS Tutorials page for more
such tutorials.
If you are looking for skilled and
experienced VueJS developers, contact
Bacancy Technology to hire VueJs
developers.
Thank You
www.bacancytechnology.com

More Related Content

What's hot (20)

Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentation
sourabh aggarwal
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
Ran Mizrahi
 
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter PilgrimJavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
Java9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidadJava9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidad
David Gómez García
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
davidchubbs
 
ExtJs Basic Part-1
ExtJs Basic Part-1ExtJs Basic Part-1
ExtJs Basic Part-1
Mindfire Solutions
 
Dependency Injection @ AngularJS
Dependency Injection @ AngularJSDependency Injection @ AngularJS
Dependency Injection @ AngularJS
Ran Mizrahi
 
Code generation with javac plugin
Code generation with javac pluginCode generation with javac plugin
Code generation with javac plugin
Oleksandr Radchykov
 
What's new in Java EE 6
What's new in Java EE 6What's new in Java EE 6
What's new in Java EE 6
Antonio Goncalves
 
Workshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & ReduxWorkshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & Redux
Visual Engineering
 
Mobile Day - React Native
Mobile Day - React NativeMobile Day - React Native
Mobile Day - React Native
Software Guru
 
Angular 1 + es6
Angular 1 + es6Angular 1 + es6
Angular 1 + es6
장현 한
 
Kubernetes
KubernetesKubernetes
Kubernetes
Lhouceine OUHAMZA
 
To inject or not to inject: CDI is the question
To inject or not to inject: CDI is the questionTo inject or not to inject: CDI is the question
To inject or not to inject: CDI is the question
Antonio Goncalves
 
Mobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast diveMobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast dive
epamspb
 
"Migrate large gwt applications - Lessons Learned" By Harald Pehl
"Migrate large gwt applications - Lessons Learned" By Harald Pehl"Migrate large gwt applications - Lessons Learned" By Harald Pehl
"Migrate large gwt applications - Lessons Learned" By Harald Pehl
GWTcon
 
React Native: JS MVC Meetup #15
React Native: JS MVC Meetup #15React Native: JS MVC Meetup #15
React Native: JS MVC Meetup #15
Rob Gietema
 
Workshop 2: JavaScript Design Patterns
Workshop 2: JavaScript Design PatternsWorkshop 2: JavaScript Design Patterns
Workshop 2: JavaScript Design Patterns
Visual Engineering
 
Complete Java Course
Complete Java CourseComplete Java Course
Complete Java Course
Lhouceine OUHAMZA
 
Fifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 MinutesFifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 Minutes
glassfish
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentation
sourabh aggarwal
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
Ran Mizrahi
 
Java9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidadJava9 Beyond Modularity - Java 9 más allá de la modularidad
Java9 Beyond Modularity - Java 9 más allá de la modularidad
David Gómez García
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
davidchubbs
 
Dependency Injection @ AngularJS
Dependency Injection @ AngularJSDependency Injection @ AngularJS
Dependency Injection @ AngularJS
Ran Mizrahi
 
Code generation with javac plugin
Code generation with javac pluginCode generation with javac plugin
Code generation with javac plugin
Oleksandr Radchykov
 
Workshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & ReduxWorkshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & Redux
Visual Engineering
 
Mobile Day - React Native
Mobile Day - React NativeMobile Day - React Native
Mobile Day - React Native
Software Guru
 
Angular 1 + es6
Angular 1 + es6Angular 1 + es6
Angular 1 + es6
장현 한
 
To inject or not to inject: CDI is the question
To inject or not to inject: CDI is the questionTo inject or not to inject: CDI is the question
To inject or not to inject: CDI is the question
Antonio Goncalves
 
Mobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast diveMobile Open Day: React Native: Crossplatform fast dive
Mobile Open Day: React Native: Crossplatform fast dive
epamspb
 
"Migrate large gwt applications - Lessons Learned" By Harald Pehl
"Migrate large gwt applications - Lessons Learned" By Harald Pehl"Migrate large gwt applications - Lessons Learned" By Harald Pehl
"Migrate large gwt applications - Lessons Learned" By Harald Pehl
GWTcon
 
React Native: JS MVC Meetup #15
React Native: JS MVC Meetup #15React Native: JS MVC Meetup #15
React Native: JS MVC Meetup #15
Rob Gietema
 
Workshop 2: JavaScript Design Patterns
Workshop 2: JavaScript Design PatternsWorkshop 2: JavaScript Design Patterns
Workshop 2: JavaScript Design Patterns
Visual Engineering
 
Fifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 MinutesFifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 Minutes
glassfish
 

Similar to How to build to do app using vue composition api and vuex 4 with typescript (20)

Simple React Todo List
Simple React Todo ListSimple React Todo List
Simple React Todo List
Ritesh Chaudhari
 
To-Do App With Flutter: Step By Step Guide
To-Do App With Flutter: Step By Step GuideTo-Do App With Flutter: Step By Step Guide
To-Do App With Flutter: Step By Step Guide
Biztech Consulting & Solutions
 
State manager in Vue.js, from zero to Vuex
State manager in Vue.js, from zero to VuexState manager in Vue.js, from zero to Vuex
State manager in Vue.js, from zero to Vuex
Commit University
 
Introducing Vuex in your project
Introducing Vuex in your projectIntroducing Vuex in your project
Introducing Vuex in your project
Denny Biasiolli
 
Introduction to React for Frontend Developers
Introduction to React for Frontend DevelopersIntroduction to React for Frontend Developers
Introduction to React for Frontend Developers
Sergio Nakamura
 
Building user interface with react
Building user interface with reactBuilding user interface with react
Building user interface with react
Amit Thakkar
 
React outbox
React outboxReact outbox
React outbox
Angela Lehru
 
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
Daniel Fisher
 
AngularJS - Services
AngularJS - ServicesAngularJS - Services
AngularJS - Services
Nir Kaufman
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future Task
Somenath Mukhopadhyay
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법
Jeado Ko
 
React redux
React reduxReact redux
React redux
Michel Perez
 
Intro react js
Intro react jsIntro react js
Intro react js
Vijayakanth MP
 
Fundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfFundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdf
StephieJohn
 
Owl: The New Odoo UI Framework
Owl: The New Odoo UI FrameworkOwl: The New Odoo UI Framework
Owl: The New Odoo UI Framework
Odoo
 
How to Build ToDo App with Vue 3 + TypeScript
How to Build ToDo App with Vue 3 + TypeScriptHow to Build ToDo App with Vue 3 + TypeScript
How to Build ToDo App with Vue 3 + TypeScript
Katy Slemon
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express js
Ahmed Assaf
 
using Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'susing Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API's
Antônio Roberto Silva
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
Jeff Durta
 
React lecture
React lectureReact lecture
React lecture
Christoffer Noring
 
State manager in Vue.js, from zero to Vuex
State manager in Vue.js, from zero to VuexState manager in Vue.js, from zero to Vuex
State manager in Vue.js, from zero to Vuex
Commit University
 
Introducing Vuex in your project
Introducing Vuex in your projectIntroducing Vuex in your project
Introducing Vuex in your project
Denny Biasiolli
 
Introduction to React for Frontend Developers
Introduction to React for Frontend DevelopersIntroduction to React for Frontend Developers
Introduction to React for Frontend Developers
Sergio Nakamura
 
Building user interface with react
Building user interface with reactBuilding user interface with react
Building user interface with react
Amit Thakkar
 
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
2008 - TechDays PT: WCF, JSON and AJAX for performance and manageability
Daniel Fisher
 
AngularJS - Services
AngularJS - ServicesAngularJS - Services
AngularJS - Services
Nir Kaufman
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future Task
Somenath Mukhopadhyay
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법
Jeado Ko
 
Fundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfFundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdf
StephieJohn
 
Owl: The New Odoo UI Framework
Owl: The New Odoo UI FrameworkOwl: The New Odoo UI Framework
Owl: The New Odoo UI Framework
Odoo
 
How to Build ToDo App with Vue 3 + TypeScript
How to Build ToDo App with Vue 3 + TypeScriptHow to Build ToDo App with Vue 3 + TypeScript
How to Build ToDo App with Vue 3 + TypeScript
Katy Slemon
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express js
Ahmed Assaf
 
using Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'susing Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API's
Antônio Roberto Silva
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
Jeff Durta
 

More from Katy Slemon (20)

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
Katy Slemon
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
Katy Slemon
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
Katy Slemon
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
Katy Slemon
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
Katy Slemon
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
Katy Slemon
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
Katy Slemon
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
Katy Slemon
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Katy Slemon
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
Katy Slemon
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
Katy Slemon
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
Katy Slemon
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
Katy Slemon
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
Katy Slemon
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
Katy Slemon
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Katy Slemon
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
Katy Slemon
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
Katy Slemon
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
Katy Slemon
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
Katy Slemon
 
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
Katy Slemon
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
Katy Slemon
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
Katy Slemon
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
Katy Slemon
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
Katy Slemon
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
Katy Slemon
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
Katy Slemon
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
Katy Slemon
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Katy Slemon
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
Katy Slemon
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
Katy Slemon
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
Katy Slemon
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
Katy Slemon
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
Katy Slemon
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
Katy Slemon
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Katy Slemon
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
Katy Slemon
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
Katy Slemon
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
Katy Slemon
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
Katy Slemon
 

Recently uploaded (20)

Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 

How to build to do app using vue composition api and vuex 4 with typescript

  • 1. How to Build To- do App using Vue Composition API and Vuex 4 with Typescript www.bacancytechnology.com
  • 2. Quick Summary: Vue Composition API- Organized, Readable, and Understandable
  • 4. In this tutorial, we will learn and explore Vue Composition API. You might have heard about it, but if not then don’t worry at all! We will start from the basics. For knowing Vue Composition API in a better way you must have knowledge about Options API, we will discuss that too! I would suggest you visit my previous blog of the Vue 3 Tutorial series- How to Build To-do App with Vue 3 Typescript for setting up the basic demo project because in this tutorial we will be using the same github repository.
  • 6. Ineffective patterns for reusing logic and component Poor readability when component grows larger Code gets complex and difficult to manage when the project size increases Creates confusion and makes it difficult to use Typescript with ‘this Vue Composition API is function-based APIs that provides flexibility, improves code readability, and helps to maintain component logic. The main reason for introducing Vue Composition API was to address the limitations of Options API as the component gets larger. Here are some of the limitations associated with Options API-
  • 8. You might have seen this image if you are learning Vue Composition API. Let’s see briefly what does it mean. The difference in the component because of Vue Composition API You will notice a setup() function is the major change. It comprises the component’s logic. In Options API we used to define data, methods, lifecycle, etc separately as a component option, but due to composition API, setup() function will consist of all these. You might not understand the impact of this update until your component size grows larger. If you worked with a large project having complex component code or have to understand other developers’ code, you might understand the significance of code understandability and readability
  • 9. Vue Composition API sorts the component code and makes the logic reusable in a much better way Let’s take a sample code from the Github repository: Vue 3 Typescript, which we have built in the previous blog- How to Build a To-do App with Typescript: Vue 3 Tutorial.
  • 10. The One with Composition API export default defineComponent({ name: "Home", setup() { const tasks = ref([]); // ref is used to make the parameter reactive const store = useStore(); //alternative to Vue prototype of this.$store tasks.value = store.state.tasks; //this is the way to write methods const setTaskComplete = (task: Task): void => { store.commit(MutationType.CompleteTask, task); }; const deleteTask = (task: Task) => { store.commit(MutationType.DeleteTask, task); };
  • 11. // To support two-way data binding return { tasks, setTaskComplete, deleteTask }; } }); </script> On the contrary, you can see that the setup() function has combined all the six components together, which increases the readability and understandability of the code.
  • 12. Steps: How to Build To-do App using Vue Composition API and Vuex 4 with Typescript.
  • 13. Visit Vue 3 Tutorial with Typescript blog to create the vue-typescript project from scratch or click here to clone the vue-typescript-demo. For implementing Vue Composition API with Typescript follow the below steps. 1. Integrating Vuex 4 In the previous, files were written in Javascript with partial Typescript, but here we will update all the files with pure Typescript. For integrating Vuex 4 with Typescript, we will need to update two files: store/index.js and store/mutations.js.
  • 14. store/index.js Open store/index.js and update the file with the following code. import Task from "@/models/Task"; import { createStore, Store as VuexStore, CommitOptions } from "vuex"; import { Mutations, mutations } from "./mutations"; export const store = createStore({ state: { tasks: [ { name: "Demo for VueJS and TS", createdAt: new Date(), updatedAt: new Date(), completed: false, },
  • 15. }, ] as Task[], }, mutations, actions: {}, modules: {}, }); //to make the store globally accessible export function useStore() { return store as Store; } export type Store = Omit<VuexStore<any>, "commit"> & { commit<K extends keyof Mutations, P extends Parameters<Mutations[K]>[1]>( key: K, payload: P, options?: CommitOptions ): ReturnType<Mutations[K]>; };
  • 16. Use the createStore() method to create Vuex store. For using the store in different components export the useStore function. Thus, the complete store is accessible across our entire application. For accessing the store in the component, we need to inject it into the app. Thankfully, the Vue-CLI had already imported the entire store and passed it within the Vue instance of our application. Explanation Moving towards mutations.
  • 17. store/mutation.ts Mutations are methods used for modifying the store state. Mutations accept the state as its first argument and payload as the second and then updates the state with the received payload. As per the recommendation by Vuex official doc, we will use constants for the mutation types. Open store/mutation.ts file and update it with the following code below.
  • 18. import { MutationTree } from "vuex"; import { findIndex } from "lodash"; export enum MutationType { SetTask = "SET_TASKS", CompleteTask = "COMPLETE_TASK", DeleteTask = "REMOVE_TASK" } export type Mutations = { [MutationType.SetTask](state: any, task: any): void; [MutationType.CompleteTask](state: any, task: any): void; [MutationType.DeleteTask](state: any, task: any): void; };
  • 19. export const mutations: MutationTree<any> & Mutations = { [MutationType.SetTask](state, task) { state.tasks.push(task); }, [MutationType.DeleteTask](state, task) { let taskIndex = findIndex(state.tasks, task); state.tasks.splice(taskIndex, ++taskIndex); }, [MutationType.CompleteTask](state: any, task: any) { const taskIndex = findIndex(state.tasks, task); state.tasks[taskIndex].completed = true; } };
  • 20. Vuex package provides a generic type- MutationTree. It is used for declaring the type of mutation tree. MutationTypes enum stores all the possible names of mutations. Further, declaring a contract (types) for every MutationType. Create a variable named mutations for storing all the implemented mutations. The MutationTree < State > & Mutations ensures that the type is implemented correctly for avoiding Typescript errors. Explanation
  • 21. 2. Components using Composition API Implementing component API in the files – AddTask.vue and Home.vue. For that, you need to modify the code within < script > < script / > AddTask.vue <script lang="ts"> import { defineComponent, ref } from "vue"; import Task from "@/models/Task"; import { useStore } from "@/store"; import { MutationType } from "@/store/mutations"; import { useRouter } from "vue-router";
  • 22. export default defineComponent({ name: "AddTask", setup() { const taskName = ref(""); const router = useRouter(); // Substitute of Vue prototype this.$router const store = useStore(); const addTask = (): void => { const newTask = new Task(taskName.value); store.commit(MutationType.SetTask, newTask); taskName.value = ""; router.push({ path: "/" }); }; return { taskName, addTask }; } }); </script>
  • 23. As the name suggests, it is used for adding new tasks to the to-do list. Whenever the user clicks the button Add Task, the addTask function commits the SetTask mutation which will add the newly added task to the existing tasks list. Once done, the UI is updated. What’s happening in this component? Home.vue <script lang="ts"> import { defineComponent, ref } from "vue"; import Task from "@/models/Task"; import { useStore } from "@/store"; import { MutationType } from "@/store/mutations";
  • 24. export default defineComponent({ name: "Home", setup() { const tasks = ref([]); const store = useStore(); tasks.value = store.state.tasks; const setTaskComplete = (task: Task): void => { store.commit(MutationType.CompleteTask , task); }; const deleteTask = (task: Task) => { store.commit(MutationType.DeleteTask, task); }; </script>
  • 25. return { tasks, setTaskComplete, deleteTask }; } }); The component is responsible for displaying and updating (marking it done or deleting it) the to-do list. Whenever the user clicks the tick button, MutationType CompleteTask is triggered with an argument task, for marking the task as done. Whenever the user clicks the tick button, MutationType DeleteTask is triggered with an argument task, for deleting the task as done. Once done, the UI is updated. What’s happening in this component?
  • 27. ●Integrate Vuex 4 with Typescript ●Implement Vue Composition API with Typescript ●Source code- Github Repository We have mostly used the major feature releases of Vuex 4 and integrated it with the Composition API in Vue 3 to develop a small demo app. With the practical implementation, we have explored the theoretical side of Composition API and seen how it is different than Options API.
  • 28. I hope you’ve learned a great deal from the tutorial. If you have any suggestions or questions please feel free to comment below. Visit the VueJS Tutorials page for more such tutorials. If you are looking for skilled and experienced VueJS developers, contact Bacancy Technology to hire VueJs developers.