Today we will describe how to effectively use Typescript with VueJS. I prefer modular code bases as they can follow some S.O.L.I.D principles: Single Responsibility, Open-Close Principle, and Interface (Type) Segregation. The task for to day is; Given a Vue-Router
and associated routes, create an array of relevant properties for a MainNavigation
component.
TLDR-Code example
The Code
Modal State Management - Using Pinia we will handle state for modals, pop-up, pop-overs, and message. Using state management will help keep snippets together based on their functionality. We will also neither have to
provide
norinject
the state as we would withreactive
orref
objects.
Main Navigation - A presentation component which will house our top navigation bar. The navigation bar will have a hamburger menu that will toggle based on a media queries. Having a json file or a module can keep the associated data in a single location. As the project gets bigger, It can prevent duplication, improve maintainability (making source control history streamlined), and provides a single source of truth for navigation. We will add a bottom navigation page as well in the future.
Main Application - In the main application
./src/App.vue
import and render the main navigation component.
Route
- Create
./src/router/routes.ts
which will contain an array of routes. These routes can have metadata which can be anything. The data can be attached to events, analytics, to protect routes, or refresh data from backend(database). The possibilities are endless, but we will cover that in a later topic.
2.Take the scaffolded ./src/router/index.ts
and break it into parts. Break the file into the following parts.
Refactoring/Stretch Goals
In the
MainNavigation
module located atsrc/components/navigation/main-navigation.vue
theuseModal
store can be destructured by using thestoreToRefs
provided by piñia see docs.Destructure route in
RouterLink
loop. This will clean up the syntax a bit and reduce the amount of code that is written. You can always destructure additional parameters as needed.
Top comments (0)