# Vue工程项目中怎么定义常量?
在Vue的标准化开发中我们应该怎么定义一些系统中字符串、数字、数组、对象、数组对象集合类的常量值呢?
这应该是有标准化定义的。还是回到问题:Vue工程项目中怎么定义常量?
# 最佳实践示例
在Vue工程化中。
src/
constants/
index.js // 入口文件
api.js // API相关常量
routes.js // 路由相关常量
ui.js // UI相关常量
regex.js // 正则表达式常量
1
2
3
4
5
6
7
2
3
4
5
6
7
constants/index.js的代码编写:
export * from './api'
export * from './routes'
export * from './ui'
export * from './regex'
1
2
3
4
2
3
4
constants/api.js代码编写:
// API相关常量
export const API_CONFIG = {
BASE_URL: process.env.VUE_APP_API_BASE_URL || 'https://api.example.com',
TIMEOUT: 10000,
VERSION: 'v1'
}
export const HTTP_METHODS = {
GET: 'GET',
POST: 'POST',
PUT: 'PUT',
DELETE: 'DELETE'
}
export const API_ENDPOINTS = {
USERS: '/users',
PRODUCTS: '/products',
ORDERS: '/orders'
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
定义常量文件。如:src/constants/data.js。
// src/constants/data.js
// 用户角色数组常量
export const USER_ROLES = [
{ id: 1, label: '管理员', value: 'admin', permissions: ['read', 'write', 'delete'] },
{ id: 2, label: '普通用户', value: 'user', permissions: ['read', 'write'] },
{ id: 3, label: '访客', value: 'guest', permissions: ['read'] }
]
// 产品分类数组常量
export const PRODUCT_CATEGORIES = [
{ id: 1, name: '电子产品', code: 'electronics', icon: '📱' },
{ id: 2, name: '服装', code: 'clothing', icon: '👕' },
{ id: 3, name: '食品', code: 'food', icon: '🍎' },
{ id: 4, name: '家居', code: 'home', icon: '🏠' }
]
// 状态选项数组常量
export const STATUS_OPTIONS = [
{ value: 'pending', label: '待处理', color: 'orange' },
{ value: 'processing', label: '处理中', color: 'blue' },
{ value: 'completed', label: '已完成', color: 'green' },
{ value: 'cancelled', label: '已取消', color: 'red' }
]
// 默认导出所有常量
export default {
USER_ROLES,
PRODUCT_CATEGORIES,
STATUS_OPTIONS
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
引入方式:
// 方式1:
import { USER_ROLES } from '@/constants/data'
// 推荐方式二:
import { REGEX, API_CONFIG } from '@/constants'
1
2
3
4
5
2
3
4
5