vue3学习之axios、mockjs、nswag

axios、mockjs

安装

npm i --save axios
npm i --save mockjs

axios、mockjs使用

创建 src\api 目录

添加http.ts

import axios from "axios";
 
let http = axios.create({
  baseURL: "",
  timeout: 10000,
});

// 拦截器的添加
http.interceptors.request.use(
  (config) => {
    console.log("加载中");
    return config;
  },
  (err) => {
    console.log("网络异常");
    return Promise.reject(err);
  }
);
 
//响应拦截器
http.interceptors.response.use(
  (res) => {
    return res.data;
  },
  (err) => {
    console.log("请求失败");
    return Promise.reject(err);
  }
);
export default http;

添加mockApi.ts

import http from "./http";
import type { User } from "./testexport";

export default {
 
  //用户列表
  findAll() {
    return http({
      url: `/api/mockGetList`,
      method: "get",
    });
  },
 
  //添加用户
  addUser(user:User) {
    return http({
      url: `/api/add`,
      method: "post",
      data: user,
    });
  },
}

添加testexport.ts

export type User = {
    id: string;
    account: string;
    password: string;
    address: string;
  }
  
export function TestExport() {
  console.log("TestExport 执行");  
}

创建 src\mock 目录 添加index.ts

// 引入mockjs
import Mock from "mockjs";
 
// 获取 mock.Random 对象
const Random = Mock.Random;
 
// 使用mockjs模拟数据
let tableList = [
    {
        id: "E897e36C-fD41-f8Af-AA12-e436B6C5181e",
        account: "admin",
        password: "123456",
        address: "asdf@asdf.com",
    },
    {
        id: "C6b1566b-ABcD-17bB-F702-636dcC8De6Ff",
        account: "zhangsan",
        password: "123qwe",
        address: "asdf@asdf.com",
    },
]
 
// for (let i = 0; i < 20; i++) {
//   let newObject = {
//     id: Random.guid(), // 获取全局唯一标识符
//     account: /^[a-zA-Z0-9]{4,6}$/,
//     password: /^[a-zA-Z]\w{5,17}$/,
//     address: /[1-9]\d{7,10}@qq\.com/,
//   };
//   tableList.push(newObject);
// }
 
/** get请求
 * 获取用户列表
 */
Mock.mock("/api/mockGetList", "get", () => {
  return {
    code: "0",
    data: tableList,
  };
 
});
 
 
/** post请求添加表格数据 */
Mock.mock("/api/add", "post", (params) => {
  let newData = JSON.parse(params.body);
  newData.id = Random.guid();
  tableList.push(newData);
  return {
    code: "0",
    message: "success",
    data: tableList,
  };
});

运行效果


nswag

NSwag CommandLine

安装 nswag

npm install nswag --save-dev

添加 nswag 文件夹

Templates模板,如果需要定制可拷贝相关.liquid文件调整

创建 nswag.json

#生成 nswag.json 复制到/nswag目录
.\node_modules\.bin\nswag new
nswag.json调整
{
  "runtime": "Net60",
  "defaultVariables": null,
  "documentGenerator": {
    "fromDocument": {
      "url": "http://xxx/swagger.json",
      "output": null,
      "newLineBehavior": "Auto"
    }
  },
  "codeGenerators": {
    "openApiToTypeScriptClient": {
      "className": "{controller}ServiceProxy",
      "moduleName": "",
      "namespace": "",
      "typeScriptVersion": 2.7,
      "template": "Axios",
      "promiseType": "Promise",
      "httpClass": "HttpClient",
      "withCredentials": false,
      "useSingletonProvider": false,
      "injectionTokenType": "OpaqueToken",
      "rxJsVersion": 6.0,
      "dateTimeType": "DayJS",
      "nullValue": "Undefined",
      "generateClientClasses": true,
      "generateClientInterfaces": false,
      "generateOptionalParameters": false,
      "exportTypes": true,
      "wrapDtoExceptions": false,
      "exceptionClass": "ApiException",
      "clientBaseClass": "ServiceProxyBase",
      "wrapResponses": false,
      "wrapResponseMethods": [],
      "generateResponseClasses": true,
      "responseClass": "SwaggerResponse",
      "protectedMethods": [],
      "configurationClass": null,
      "useTransformOptionsMethod": true,
      "useTransformResultMethod": true,
      "generateDtoTypes": true,
      "operationGenerationMode": "MultipleClientsFromFirstTagAndPathSegments",
      "markOptionalProperties": false,
      "generateCloneMethod": false,
      "typeStyle": "Class",
      "enumStyle": "Enum",
      "useLeafType": false,
      "classTypes": [],
      "extendedClasses": [],
      "extensionCode": null,
      "generateDefaultValues": true,
      "excludedTypeNames": [],
      "excludedParameterNames": [],
      "handleReferences": false,
      "generateConstructorInterface": true,
      "convertConstructorInterfaceData": false,
      "importRequiredTypes": true,
      "useGetBaseUrlMethod": false,
      "baseUrlTokenName": null,
      "queryNullValue": "",
      "useAbortSignal": false,
      "inlineNamedDictionaries": false,
      "inlineNamedAny": false,
      "templateDirectory": "./templates",
      "typeNameGeneratorType": null,
      "propertyNameGeneratorType": null,
      "enumNameGeneratorType": null,
      "serviceHost": null,
      "serviceSchemes": null,
      "output": "../src/services/ServiceProxies.ts",
      "newLineBehavior": "Auto"
    }
  }
}

添加refresh.bat

"..\node_modules\.bin\nswag" run /runtime:Net60

生成代理

package.json配置nswag

  "scripts": {
    "nswag": "cd nswag &.\\refresh.bat",
  } 

添加 /src/services/ServiceProxyBase.ts

import { AxiosResponse } from "axios";
 
export class ServiceProxyBase {
    protected transformResult(url: string, response: AxiosResponse, processor: (response: AxiosResponse) => Promise<any>): Promise<any> {
        // if(response.data.result){
        //     response.data=response.data.result;
        // }
        console.log(response)
        return processor(response);
    }
}

执行生成

npm run nswag

使用Proxy

import { xxxServiceProxy } from '/@/services/ServiceProxies';

export function getConfiguration() {
  const _xxxServiceProxy = new xxxServiceProxy();
  return _xxxServiceProxy.configuration();
}

关于SPA的SEO优化

关于SPA的SEO解决方案
浅谈:SPA 及其 SEO 优化方案
原本是打算用vue弄个前台站点,但是看了关于单页面对SEO不太友好,优化也要做一些额外到工作,还是老实用服务端渲染到多页面方式做。学习示例代码已上传。

posted @ 2023-04-22 21:59  ddrsql  阅读(311)  评论(0编辑  收藏  举报