文件结构
生成一个vue项目
- 环境配置,安装 Vue-cli 3.0 脚手架工具
npm install -g @vue/cli
- 初始化项目
vue create <projectName>
- 添加依赖
yarn add vue-router -S
yarn add vuex -S
yarn add axios -S
yarn add vue-i18n -S
配置vue-router
- 在src下创建router文件夹和下面的index.js
import { createRouter,createWebHashHistory} from "vue-router";
const routes = [
{
path: "/",
redirect: "/home",
},
{
path: "/home",
name: "home",
component: () => import('@/pages/Home'),
},
];
export default createRouter({
history: createWebHashHistory(),
routes,
});
- 修改main.js
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
const app = createApp(App);
app.use(router);
app.mount('#app');
- 修改App.vue
<template>
<router-view />
</template>
<script>
export default {
name: 'App',
}
</script>
配置vuex
- 在src下创建store文件夹和下面的index.js、getters.js、modules/user.js
index.js
import { createStore } from "vuex";
import getters from './getters';
import user from './modules/user';
export default createStore({
getters,
modules: {
user,
},
});
getters.js
const getters = {
userId: (state) => state.user.id,
email: (state) => state.user.email,
phone: (state) => state.user.phone,
avatar: (state) => state.user.avatar,
nickname: (state) => state.user.nickname,
role: (state) => state.user.role,
};
export default getters;
user.js
const user = {
// 声明变量
state: {
id: '',
email: '',
phone: '',
nickname: '',
avatar: '',
role: {},
},
// 修改变量(state不能直接赋值修改,只能通过mutations)
mutations: {
// 参数一:state,参数二:新值
SET_USERID: (state, id) => {
state.id = id;
},
SET_EMAIL: (state, email) => {
state.email = email;
},
SET_PHONE: (state, phone) => {
state.phone = phone;
},
SET_NAME: (state, nickname) => {
state.nickname = nickname;
},
SET_AVATAR: (state, avatar) => {
state.avatar = avatar;
},
SET_USER_ROLE: (state, role) => {
state.role = role;
},
},
// mutations的值由actions传入
actions: {
GET_USER_INFO({ commit }, userInfo) {
commit('SET_USERID', userInfo.id);
commit('SET_EMAIL', userInfo.email);
commit('SET_PHONE', userInfo.phone);
commit('SET_NAME', userInfo.name);
commit('SET_AVATAR', userInfo.avatar);
commit('SET_USER_ROLE', userInfo.role);
}
},
};
export default user;
- 修改main.js
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
const app = createApp(App);
app.use(router);
app.use(store);
app.mount('#app');
配置axios
- 新建一个request.js文件
import axios from 'axios';
import qs from 'qs';
const baseConfig = {
// `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
baseURL: 'https://xxx.com',
// `timeout` 指定请求超时的毫秒数(0 表示无超时时间),如果请求话费了超过 `timeout` 的时间,请求将被中断
timeout: 20000,
// `headers` 是即将被发送的自定义请求头
headers: {
'X-Requested-With': 'XMLHttpRequest',
},
// `paramsSerializer` 是一个负责 `params` 序列化的函数
paramsSerializer: (params) => qs.stringify(params, { arrayFormat: 'brackets', allowDots: true }),
};
// 在发送请求之前做些什么
const formatRequestConfig = (config) => {
console.log(config);
return config;
};
// 对请求错误做些什么
const err = ({ response }) => {
if (!response) {
message.error('网络开小差啦');
} else {
const { status } = response;
switch (status) {
case 403:
// 处理403
break;
case 401:
window.location.href = 'http://localhost:8080';
break;
case 400:
if (!response.config.ignoreError) {
// 显示错误信息
}
break;
default:
break;
}
}
return Promise.reject(response);
};
// 新建一个 axios 实例
const service = axios.create(baseConfig);
// 添加请求拦截器
service.interceptors.request.use(formatRequestConfig, err);
export {
service as axios,
};
- 创建某个API文件
import { axios as request } from '../utils/request';
export default class Users {
static fetchById = (userId) => request.get(`/users/${userId}`);
};
- 使用
const user = await Users.fetchById('123');
配置vue-i18n
- 在src下创建locales文件夹和下面的index.js、zh-CN.js、en-US.js
index.js
import { createI18n } from 'vue-i18n';
import zh from './zh-CN';
import en from './en-US';
const defaultLanguage = 'zh-CN';
const i18n = createI18n({
locale: defaultLanguage,
messages: { zh, en },
});
export { i18n };
zh-CN.js
export default {
common: {
ok: '确认',
save: '保存',
return: '返回',
cancel: '取消',
submit: '提交',
query: '查询',
reset: '重置',
}
};
-修改main.js
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
import { i18n } from './locales';
const app = createApp(App);
app.use(router);
app.use(store);
app.use(i18n);
app.mount('#app');
- 使用
<template>
<div>{{ $t('common.ok') }}</div>
</template>