vue2企业级项目(三)
引入mockjs,i18n
1、mockjs
-
项目下载依赖
npm install --save-dev mock
-
根目录创建
mock
文件夹,并创建mock/index.js
import Mock from "mockjs";// 设置全局延时 没有延时的话有时候会检测不到数据变化 建议保留 Mock.setup({timeout: "300-600", });// 引入全部的modules内全部js文件,并分流进行处理 const modulesFiles = require.context("./modules", true, /\.js$/); const modules = modulesFiles.keys().reduce((modules, modulePath) => {const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, "$1"); // 正则提取子文件名称const value = modulesFiles(modulePath); // 获取文件对象modules[moduleName] = value.default; // 获取文件默认导出return modules; }, {});// 动态添加mock for (let fileName in modules) {// 因为mock匹配规则是从上到下的,所以要对path长度进行排序// 避免提前匹配导致错误问题modules[fileName].sort((last, next) => next.path.length - last.path.length,);// 添加mock匹配规则modules[fileName].forEach((item) => {let regexp = new RegExp(process.env.VUE_APP_PREFIX + item.path);Mock.mock(regexp, item.method, item.dispose.action);}); }// mock验证 - 给ajax用的 export function proxyValid(url, method, date) {for (let fileName in modules) {modules[fileName].forEach((item) => {if (item.path === url && item.method === method) {const validRes = Mock.valid(item.dispose.template, date);if (validRes && validRes.length === 0) return true; // 验证通过// 验证不通过console.group(url.replace(/http:\/\//, ""));console.log("valid response data :>>> url: ", url);console.log("valid response data :>>> validMsg: ", validRes);console.groupEnd();}});} }// mockRandom继承添加创出电话号码 Mock.Random.extend({phone: function() {let phonePrefix = ["132", "135", "189", "135", "189"]; // 自己写前缀哈return Mock.Random.pick(phonePrefix) + Mock.mock(/\d{8}/); // Number()}, });export default Mock;
-
创建
mock/mockPort.js
import Qs from "qs"; import { checkDataType } from "@/utils/utils";function MockPort({ template, action }) {this.template = template; // 模板this.action = action.bind(this); // 返回值// 解析返回get参数方法this.queryBackRes = function(url = "") {const urlArr = url.split("?");const dataString = urlArr[1] || "";return Qs.parse(dataString);};// 解析返回post参数方法this.paramsBackRes = function(body) {if (checkDataType(body, "string")) return JSON.parse(body);else return body;};// 分页获取listthis.getPagingList = function(pagination, list) {let { pageNumber, pageSize } = pagination;const startIndex = (pageNumber - 1) * pageSize; // 开始截取位置const endIndx = pageNumber * pageSize; // 结束截取位置const totalPages = Math.ceil(list.length / pageSize); // 总页码数let rows =pageNumber > totalPages ? [] : list.slice(startIndex, endIndx);return { rows, total: list.length };};// 检查是否携带tokenthis.checkToken = function(options, resObj) {let query = this.queryBackRes(options.url);if (query.id_token === "123456789") return resObj;return {statusCode: 401,code: -1,msg: "账户验证失败,请重新登录",data: null,};}.bind(this); }export default MockPort;
-
创建
mock/modules/test.js
示例import MockPort from "../mockPort"; // 解析获取git数据function testGet() {return new MockPort({template: {status: 1,data: "test",},action(options) {let query = this.queryBackRes(options.url);this.template.data += query;return this.template;},}); }function testPost() {return new MockPort({template: {status: 1,data: "test",},action(options) {let query = this.paramsBackRes(options.body);this.template.data += query;return this.template;},}); }export default [{ path: "/testGet", method: "get", dispose: testGet() },{ path: "/testPost", method: "post", dispose: testPost() }, ];
-
src
目录下创建api/mock.js
示例import request from "@/utils/request.js";export const testGet = (params) => request.get("/testGet", params); export const testPost = (params) => request.post("/testPost", params);
-
main.js
添加一下内容...if (process.env.NODE_ENV === "development") require("../mock/index"); ...
-
根目录创建
vue.config.js
module.exports = {devServer: {open: true,port: "8080",overlay: {warning: false,error: false,},}, };
2、i18n
-
项目下载依赖
npm install vue-i18n@8.26.2 --save
-
src
目录下创建i18n/index.js
文件import Vue from "vue"; import VueI18n from "vue-i18n"; import { getStorage } from "@/utils/storage.js";Vue.use(VueI18n);// 自动引入modules文件 const modulesFiles = require.context("./modules", true, /\.js$/);const messages = modulesFiles.keys().reduce((modules, modulePath) => {const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, "$1");const value = modulesFiles(modulePath);modules[moduleName] = value.default;return modules; }, {});const i18n = new VueI18n({locale: getStorage("local") || process.env.VUE_APP_locale,messages, });export default i18n;
-
main.js
引入使用i18n
,和vuex
生成的store
是一样的 -
创建
i18n/modules/en.js
、i18n/modules/zh.js
/***********en.js***************/ export default {hello: "Hello", };/***********zh.js***************/ export default {hello: "你好", };
-
动态切换语言包
changeLanguage(type) {this.$i18n.local = type ? "en" : "zh" }