[Series] Setup Source Template for Vue 3 – Phần 2

Giới thiệu Chào tất cả các bạn, phần 1 mình đã giới thiệu tổng quát về source code và setup cơ bản về Vue 3 + Vite. Trong bài này mình tiếp tục tìm hiểu về và setup về vue-router, pinia và Vitest Nội Dung ⚡️ Vue 3, Vite, pnpm 📦 Components auto importing 🎨

Giới thiệu

Chào tất cả các bạn, phần 1 mình đã giới thiệu tổng quát về source code và setup cơ bản về Vue 3 + Vite. Trong bài này mình tiếp tục tìm hiểu về và setup về vue-router, piniaVitest

Nội Dung

Đây là cấu trúc thư mục của dự án sau khi setup.

vue-template/
 ├── public/
 |    ├── favicon.ico
 ├── src/
 |    ├── assets/
 |    |    └── logo.png
 |    ├── components/
 |    |    └── HelloWorld.vue
 |    ├── core/
 |    ├── hooks/
 |    |    └── useAuth.ts
 |    ├── layouts/
 |    |    └── BlankLayout.vue
 |    |    └── MainLayout.vue
 |    ├── pages/
 |    |    └── Dashboard.vue
 |    |    └── Error.vue
 |    |    └── NotFound.vue
 |    ├── routes/
 |    |    └── index.ts
 |    ├── stores/
 |    |    └── auth.ts
 |    ├── test/
 |    |    └── components/
 |    |    |    └── Sample.spec.ts
 |    ├── App.vue
 |    └── main.ts
 |    └── vite-env.d.ts
 |    └── vue-shim.d.ts
 ├── package.json
 ├── README.md
 ├── .cz-config.ts
 ├── .env.sample
 ├── .eslintrc
 ├── .prettierrc
 ├── .commitlint.config.cjs
 ├── tsconfig.json
 ├── tsconfig.node.json
 └── vite.config.js
 └── unocss.config.ts

Cài đặt

Trong phần này mình sẽ hướng dẫn các bạn setup về:
🍍 State Management via Pinia, Vue Router
⚙️ Unit Testing với Vitest

Bây giờ chúng ta sẽ cài vue-routerpinia từ PNPM vào dự án của mình.

Vue Router

vue-router là bộ định tuyến chính thức cho Vue.js. Chúng ta sẽ cần cài đặt version 4 tương thích với Vue 3:

$ pnpm i vue-router@4

Tạo 1 folder routes và tạo 1 file index.ts

// index.tsimport{createRouter}from'vue-router'import Homepage from'./home/Home.vue';import SignIn from'./sign-in/SignIn.vue';import Cart from'./cart/Cart.vue';exportconst routes =[{
    path:'/',
    component: MainLayout,
    requiresAuth:true,
    children:[{
        path:'dashboard',
        name:'Dashboard',component:()=>import('@pages/DashBoard.vue'),
        meta:{
          requiresAuth:true,
          headerTitle:'Dashboard',
          searchConfig:{},
          storeConfig:{},},},],},{
    path:'/login',
    component: BlankLayout,
    children:[{
        path:'login',
        name:'Login',component:()=>import('@pages/Login.vue'),},],},{
    path:'/:pathMatch(.*)*',
    name:'Page Not Found',component:()=>import('@pages/NotFound.vue'),},{
    path:'/error',
    name:'Error',component:()=>import('@pages/Error.vue'),},]exportdefaultfunction(history){returncreateRouter({
    history,
    routes
  })}

Import route vào file main.ts

import router from'./router'const app =createApp(App)
app.use(router)...

Pinia

Pinia là một trong những project mới nhất xuất hiện từ hệ sinh thái Vue và nó là công cụ quản lý trạng thái (State Management) chính thức mới cho các ứng dụng Vue.js. Api của nó rất giống với Vuex (tiền thân của nó) và nó được thiết kế để nhanh hơn và nhẹ hơn.

$ pnpm i pinia

Tạo 1 folder stores và tạo 1 file auth.ts

import{ defineStore, acceptHMRUpdate }from'pinia'interfaceIUser{
  email: string
  name: string
}exportconst useAuthStore =defineStore('auth',()=>{const isLoggedIn =ref(false)const info = ref<IUser |null>(null)constsetInfo=(user: IUser)=>{
    info.value = user
  }constsetIsLoggedIn=(value: boolean)=>{
    isLoggedIn.value = value
  }return{
    isLoggedIn,
    info,
    setInfo,
    setIsLoggedIn,}})if(import.meta.hot){import.meta.hot.accept(acceptHMRUpdate(useAuthStore,import.meta.hot))}

Import pinia vào file main.ts

import{ createPinia }from'pinia'const app =createApp(App)...
app.use(createPinia())...

Vitest

Vitest là 1 unit test framework chạy rất nhanh được cung cấp bởi Vite.

Vitest requires Vite >=v3.0.0 and Node >=v14

$ pnpm i -D vitest

thêm script chạy test vào package:

"scripts":{"dev":"vite","build":"vue-tsc && vite build","preview":"vite preview","test":"vitest"}

Chúng ta sẽ thử viết 1 vài đoạn test trong file sample.spec.ts để kiểm tra test nó đã hoạt động hay chưa.

import{ expect, test }from'vitest'test('Math.sqrt()',()=>{expect(Math.sqrt(4)).toBe(2)expect(Math.sqrt(144)).toBe(12)expect(Math.sqrt(2)).toBe(Math.SQRT2)})

Sau đó chúng ta chạy pnpm run test và kết quả là:
Screenshot 2023-02-02 at 23.18.42.png

Kết bài

Ở phần này chúng ta đã cùng nhau tìm hiểu và setup vue-router, piniatesting. Ở phần tiếp theo chúng ta sẽ cùng nhau tìm hiểu về và setup eslint, prettierrcrulecommitlint.

Nguồn

https://github.com/trungpham71198/vue-template/tree/feat/chapter-2

Nguồn: viblo.asia

Bài viết liên quan

Thay đổi Package Name của Android Studio dể dàng với plugin APR

Nếu bạn đang gặp khó khăn hoặc bế tắc trong việc thay đổi package name trong And

Lỗi không Update Meta_Value Khi thay thế hình ảnh cũ bằng hình ảnh mới trong WordPress

Mã dưới đây hoạt động tốt có 1 lỗi không update được postmeta ” meta_key=

Bài 1 – React Native DevOps các khái niệm và các cài đặt căn bản

Hướng dẫn setup jenkins agent để bắt đầu build mobile bằng jenkins cho devloper an t

Chuyển đổi từ monolith sang microservices qua ví dụ

1. Why microservices? Microservices là kiến trúc hệ thống phần mềm hướng dịch vụ,