Hướng dẫn khởi tạo dự án thương mại điện tử với Vue 3 và Element Plus

Tạo dự án và sắp xếp cấu trúc thư mục

Để bắt đầu, chúng ta sẽ tạo một dự án Vue 3 mới bằng lệnh:

npm init vue@latest

Lưu ý rằng npm yêu cầu tên gói phải **toàn chữ thường và không chứa ký tự đặc biệt**, cho phép dấu gạch ngang (-) và dấu gạch dưới (_). Khi sử dụng `npm init vue@latest`, nếu tên dự án có chữ hoa (ví dụ: MyApp), trình scaffolding sẽ phát hiện và yêu cầu bạn cung cấp một tên hợp lệ (ví dụ: my-app). Tên toàn chữ thường (ví dụ: myapp) sẽ được chấp nhận mà không cần hỏi lại.

Cấu trúc lại thư mục src

Tạo 5 thư mục mới (tên phải có chữ s ở cuối):

  1. apis ----- Thư mục chứa các hàm gọi API
  2. composables ----- Thư mục chứa các hàm组合 (composables)
  3. directives ----- Thư mục chứa các directive toàn cục
  4. styles ----- Thư mục chứa các样式 toàn cục
  5. utils ----- Thư mục chứa các hàm tiện ích

Khởi tạo Git

Dự án được tạo bởi `create-vue` mặc định không có kho lưu trữ Git, vì vậy chúng ta cần khởi tạo nó thủ công.

// Chỉ cần thực hiện lần đầu tiên
git init
git add .
git commit -m "init"

(Ghi chú: Nếu bạn đã có một terminal đang chạy lệnh `npm run dev`, đừng tắt nó. Hãy mở một terminal mới để thực hiện các lệnh Git.)

Cấu hình đường dẫn bí danh (Path Aliases)

Cấu hình đường dẫn bí danh giúp gợi ý đường dẫn khi viết code.

{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@/*": [
        "src/*"
      ]
    }
  }
}

Trong file `App.vue`, thay thế `./` bằng `@/` để kiểm tra tính năng gợi ý đường dẫn. Nếu không hoạt động, hãy thử khởi động lại VSCode.

Tích hợp Element Plus

1. Cài đặt Element Plus và plugin tự động nhập

npm i element-plus
npm install -D unplugin-vue-components unplugin-auto-import

2. Cấu hình tự động nhập theo yêu cầu

Trong file `vite.config.js` tại thư mục gốc, thêm và sửa đổi mã như sau:

// Import các plugin
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

export default defineConfig({
  plugins: [
    // Cấu hình plugin
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    }),
  ]
})

3. Kiểm tra component

Trong `App.vue`, thêm đoạn mã sau để kiểm tra component có hoạt động không:

<template>
  <el-button type="primary">i am button</el-button>
</template>

Tùy chỉnh chủ đề Element Plus

1. Cài đặt Sass

Dự án dựa trên Vite mặc định không hỗ trợ các bộ tiền xử lý CSS, cần cài đặt riêng.

npm i sass -D

2. Chuẩn bị file SCSS tùy chỉnh

Tạo file tại đường dẫn: `@/styles/element/index.scss` và định nghĩa các màu sắc theo thiết kế.

/* Chỉ cần ghi đè các biến bạn cần */
@forward 'element-plus/theme-chalk/src/common/var.scss' with (
  $colors: (
    'primary': (
      // Màu chính
      'base': #27ba9b,
    ),
    'success': (
      // Màu thành công
      'base': #1dc779,
    ),
    'warning': (
      // Màu cảnh báo
      'base': #ffb302,
    ),
    'danger': (
      // Màu nguy hiểm
      'base': #e26237,
    ),
    'error': (
      // Màu lỗi
      'base': #cf4444,
    ),
  )
)

3. Cấu hình tự động nhập

Cập nhật file `vite.config.js` để tự động nhập file SCSS tùy chỉnh và cấu hình chủ đề.

import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// Cấu hình tự động nhập Element Plus
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

export default defineConfig({
  plugins: [
    vue(),
    // ...
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [
        // 1. Cấu hình Element Plus sử dụng hệ thống màu Sass
        ElementPlusResolver({ importStyle: "sass" }),
      ],
    }),
  ],
  resolve: {
    // Chuyển đổi đường dẫn thực tế @ -> src
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  css: {
    preprocessorOptions: {
      scss: {
        // 2. Tự động nhập file SCSS tùy chỉnh để ghi đè样式
        additionalData: `
          @use "@/styles/element/index.scss" as *;
        `,
      }
    }
  }
})

Cài đặt và đóng gói Axios

1. Cài đặt Axios

npm i axios

2. Cấu hình cơ bản

Tạo file `@/utils/apiClient.js` để cấu hình instance của Axios.

import axios from 'axios'

// Tạo instance của axios
const apiClient = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 5000
})

// Bộ lọc yêu cầu của axios
apiClient.interceptors.request.use(config => {
  return config
}, error => Promise.reject(error))

// Bộ lọc phản hồi của axios
apiClient.interceptors.response.use(response => response.data, error => {
  return Promise.reject(error)
})

export default apiClient

3. Đóng gói hàm yêu cầu và kiểm tra

Tạo file `@/apis/categoryAPI.js` mới.

import apiClient from "@/utils/apiClient"

export function fetchCategories() {
  return apiClient({
    url: 'home/category/head'
  })
}

Trong file `main.js`, gọi hàm API để kiểm tra:

// Kiểm tra hàm API
import { fetchCategories } from '@/apis/categoryAPI'
fetchCategories().then(response => {
  console.log(response)
})

Thiết kế hệ thống路由

Nguyên tắc thiết kế: Nếu trang chuyển đổi là **toàn bộ trang**, đó là **router cấp 1**. Nếu nội dung chuyển đổi bên trong một router cấp 1, đó là **router cấp 2**.

Tạo các file component tương ứng:

  • @/views/MainLayout/index.vue
  • @/views/LoginPage/index.vue
  • @/views/HomePage/index.vue
  • @/views/CategoryPage/index.vue

Cấu hình router

Trong file `@/router/index.js`:

// createRouter: Tạo đối tượng instance router
// createWebHistory: Tạo router ở chế độ history

import { createRouter, createWebHistory } from 'vue-router'
import LoginPage from '@/views/LoginPage/index.vue'
import MainLayout from '@/views/MainLayout/index.vue'
import HomePage from '@/views/HomePage/index.vue'
import CategoryPage from '@/views/CategoryPage/index.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: MainLayout,
      children: [
        {
          path: '',
          component: HomePage
        },
        {
          path: 'category',
          component: CategoryPage
        }
      ]
    },
    {
      path: '/login',
      component: LoginPage
    }
  ]
})

export default router

Tài nguyên tĩnh và cài đặt Error Lens

  1. Thêm thư mục images vào thư mục assets.
  2. Thêm file common.scss vào thư mục styles.
  3. Cài đặt extension Error Lens cho VSCode.

Tự động nhập biến SCSS

Tạo file @/styles/variables.scss để chứa các biến màu chung.

$primaryColor: #27ba9b; 
$dangerColor: #e26237;
$successColor: #1dc779;
$warningColor: #ffb302;
$priceColor: #cf4444;

Cập nhật file vite.config.js:

css: {
    preprocessorOptions: {
      scss: {
        additionalData: `
          @use "@/styles/element/index.scss" as *;
          @use "@/styles/variables.scss" as *;
        `,
      }
    }
}

Kiểm tra trong App.vue:

<template>
  <RouterView />
  <div class="test">
    test scss
  </div>
</template>

<style scoped lang="scss">
.test {
  color: $priceColor;
}
</style>

Thẻ: Vue.js Element Plus Axios vite SCSS

Đăng vào ngày 8 tháng 6 lúc 21:02