search
HomeWeb Front-endVue.jsWhat is the method of encapsulating axios and using mock.js with vue3 and ts?

    Preface

    We should pay attention to distinguishing between Axios and Ajax:

    Ajax is a general term for technology, and the technical content includes: HTML or XHTML , CSS, JavaScript, DOM, XML, XSLT, and the most important XMLHttpRequest, which is used to use asynchronous data transmission (HTTP request) between the browser and the server to make local requests to achieve local refresh. The use is based on XMLHttpRequest;

    Axios is a promise-based HTTP library and a third-party library

    Main technology stack: vue3, ts, axios, mock.js, elementPlus

    1. Dependency installation and processing of axios

    1. Dependency installation

    Using asynchronous network requests is definitely inseparable from loading, message and other prompts. Today we will use it with elementPlus;

    // 安装axios 
    npm install axios --save
     
    // 安装 elementPlus
    npm install element-plus --save

    2. Global axios package

    In the utils directory under the src directory, create a new request.ts. Because TS is used, the data format needs to be defined in advance:

    • Define the format of request data return, which needs to be confirmed in advance

    • Define axios basic configuration information

    • Request interceptor: The place where all requests arrive first. We can customize the request header information here (such as token, multi-language, etc.)

    • Response interceptor: return the place where the data first arrives. , we can handle exception information here (for example: code 401 redirects to login, code 500 prompts error message)

    import axios, { AxiosInstance, AxiosError, AxiosRequestConfig, AxiosResponse } from "axios";
    import { ElMessage, ElLoading, ElMessageBox } from "element-plus";
     
    // response interface { code, msg, success }
    // 不含 data
    interface Result {
        code: number,
        success: boolean,
        msg: string
    }
     
    // request interface,包含 data
    interface ResultData<T = any> extends Result {
        data?: T
    }
     
    enum RequestEnums {
        TIMEOUT = 10000, // 请求超时 request timeout
        FAIL = 500, // 服务器异常 server error
        LOGINTIMEOUT = 401, // 登录超时 login timeout
        SUCCESS = 200, // 请求成功 request successfully
    }
     
    // axios 基础配置
    const config = {
        // 默认地址,可以使用 process Node内置的,项目根目录下新建 .env.development
        baseURL: process.env.VUE_APP_BASE_API as string,
        timeout: RequestEnums.TIMEOUT as number, // 请求超时时间
        withCredentials: true, // 跨越的时候允许携带凭证
    }
     
    class Request {
        service: AxiosInstance;
     
        constructor(config: AxiosRequestConfig) {
            // 实例化 serice
            this.service = axios.create(config);
     
            /**
             * 请求拦截器
             * request -> { 请求拦截器 } -> server
             */
            this.service.interceptors.request.use(
                (config: AxiosRequestConfig) => {
                    const token = localStorage.getItem(&#39;token&#39;) ?? &#39;&#39;;
                    return {
                        ...config,
                        headers: {
                            &#39;customToken&#39;: "customBearer " + token
                        }
                    }
                },
                (error: AxiosError) => {
                    // 请求报错
                    Promise.reject(error)
                }
            );
     
            /**
             * 响应拦截器
             * response -> { 响应拦截器 } -> client
             */
            this.service.interceptors.response.use(
                (response: AxiosResponse) => {
                    const { data, config } = response;
                    if (data.code === RequestEnums.LOGINTIMEOUT) {
                        // 表示登录过期,需要重定向至登录页面
                        ElMessageBox.alert("Session expired", "System info", {
                            confirmButtonText: &#39;Relogin&#39;,
                            type: &#39;warning&#39;
                        }).then(() => {
                            // 或者调用 logout 方法去处理
                            localStorage.setItem(&#39;token&#39;, &#39;&#39;);
                            location.href = &#39;/&#39;
                        })
                    }
                    if (data.code && data.code !== RequestEnums.SUCCESS) {
                        ElMessage.error(data);
                        return Promise.reject(data);
                    }
                    return data
                },
                (error: AxiosError) => {
                    const { response } = error;
                    if (response) {
                        this.handleCode(response.status);
                    }
                    if (!window.navigator.onLine) {
                        ElMessage.error("网络连接失败,请检查网络");
                        // 可以重定向至404页面
                    }
                }
     
            )
        }
     
        public handleCode = (code: number): void => {
            switch (code) {
                case 401:
                    ElMessage.error("登陆失败,请重新登录");
                    break;
                case 500:
                    ElMessage.error("请求异常,请联系管理员");
                    break;
                default:
                    ElMessage.error(&#39;请求失败&#39;);
                    break;
            }
        }
     
        // 通用方法封装
        get<T>(url: string, params?: object): Promise<ResultData<T>> {
            return this.service.get(url, { params });
        }
     
        post<T>(url: string, params?: object): Promise<ResultData<T>> {
            return this.service.post(url, params);
        }
        put<T>(url: string, params?: object): Promise<ResultData<T>> {
            return this.service.put(url, params);
        }
        delete<T>(url: string, params?: object): Promise<ResultData<T>> {
            return this.service.delete(url, { params });
        }
    }
     
    export default new Request(config)

    3. Actual use

    Add api/index.ts in the src directory

    • Define the parameter type of the request

    • Define the specific parameter type of the response

    Here we use the namespace in ts. In actual development, many of our APIs may have the same name with different meanings, so we use namespace for definition

    import request from "@/utils/request";
     
    namespace User {
        // login
        export interface LoginForm {
            userName: string,
            password: string
        }
    }
     
     
    export namespace System {
     
     
        export interface Info {
            path: string,
            routeName: string
        }
     
     
        export interface ResponseItem {
            code: number,
            items: Array<Sidebar>,
            success: boolean
        }
     
        export interface Sidebar {
            id: number,
            hashId: string | number,
            title: string,
            routeName: string,
            children: Array<SidebarItem>,
        }
     
        export interface SidebarItem {
            id: number,
            parentId: number,
            hashId: string | number,
            title: string,
        }
    }
     
    export const info = (params: System.Info) => {
        // response 
        if (!params || !params.path) throw new Error(&#39;Params and params in path can not empty!&#39;)
        // 这里因为是全局的一个info,根据路由地址去请求侧边栏,所需不用把地址写死
        return request.post<System.Sidebar>(params.path, { routeName: params.routeName })
    }

    Call in Vue file

    <script lang="ts" setup name="Sidebar">
    import { ref, reactive, onBeforeMount } from "vue"
    import { info } from "@/api"
    import { useRoute } from "vue-router"
    const route = useRoute();
     
    let loading = ref<boolean>(false);
    let sidebar = ref<any>({});
     
    const _fetch = async (): Promise<void> => {
        const routeName = route.name as string;
        const path = &#39;/&#39; + routeName.replace(routeName[0], routeName[0].toLocaleLowerCase()) + &#39;Info&#39;
        try {
            loading.value = true;
            const res = await info({ path, routeName });
            if (!res || !res.data) return;
            sidebar.value = res.data;
        } finally {
            loading.value = false
        }
    }
     
    onBeforeMount(() => {
        _fetch();
    })
     
    </script>

    2. Dependency installation and processing of mock.js

    1. Install dependencies

    # 安装
    npm install mockjs --save

    When used in ts , we need to throw the module in the shims-vue.d.ts file now, otherwise there will be problems with introducing errors

    /* eslint-disable */
    declare module &#39;*.vue&#39; {
      import type { DefineComponent } from &#39;vue&#39;
      const component: DefineComponent<{}, {}, any>
      export default component
    }
     
    declare module &#39;mockjs&#39;;

    2. Create the files required for the new mock

    What is the method of encapsulating axios and using mock.js with vue3 and ts?

    index.ts (belongs to the mockjs global configuration file), mockjs/javaScript/index.ts (specific data files), these two need to be paid attention to, and others do not need to be paid attention to

    1. Create a new mockjs /javaScript/index.ts (specific data file)

    Because the data here is mainly the data in the sidebar, which are all fixed, so the rules of mockjs are not used to generate data.

    import { GlobalSidebar, Sidebar } from "../../sidebar";
     
    namespace InfoSidebar {
        export type InfoSidebarParams = {
            body: string,
            type: string,
            url: string
        }
    }
     
    const dataSource: Array<GlobalSidebar> = [
        {
            mainTitle: &#39;JavaScript基础问题梳理&#39;,
            mainSidebar: [
                {
                    id: 0,
                    hashId: &#39;This&#39;,
                    title: &#39;this指向&#39;,
                    routeName: &#39;JsBasic&#39;,
                    children: [
                        {
                            id: 1,
                            parentId: 0,
                            hashId: &#39;GlobalFunction&#39;,
                            title: &#39;全局函数&#39;
                        },
                        {
                            id: 2,
                            parentId: 0,
                            hashId: &#39;ObjectMethod&#39;,
                            title: &#39;对象方法&#39;
                        },
                        {
                            id: 3,
                            parentId: 0,
                            hashId: &#39;Constructor&#39;,
                            title: &#39;构造函数&#39;
                        },
                        {
                            id: 4,
                            parentId: 0,
                            hashId: &#39;SetTimeout&#39;,
                            title: &#39;定时器、回调函数&#39;
                        },
                        {
                            id: 5,
                            parentId: 0,
                            hashId: &#39;EventFunction&#39;,
                            title: &#39;事件函数&#39;
                        },
                        {
                            id: 6,
                            parentId: 0,
                            hashId: &#39;ArrowFunction&#39;,
                            title: &#39;箭头函数&#39;
                        },
                        {
                            id: 7,
                            parentId: 0,
                            hashId: &#39;CallApplyBind&#39;,
                            title: &#39;call、apply、bind&#39;
                        },
                    ]
                },
                {
                    id: 2,
                    hashId: &#39;DeepClone&#39;,
                    title: &#39;深拷贝和浅拷贝&#39;,
                    routeName: &#39;JsBasic&#39;,
                    children: []
                }
            ]
        },
    ];
     
    export default {
        name: &#39;jsBasicInfo&#39;,
        jsBasicInfo(params: InfoSidebar.InfoSidebarParams) {
            const param = JSON.parse(params.body)
            if (!param) throw new Error("Params can not empty!");
            const data = dataSource.find((t: GlobalSidebar) => {
                return t.mainSidebar.filter((x: Sidebar) => {
                    return x.routeName === param.routeName
                })
            })
            return {
                data,
                success: true,
                code: 200
            }
        }
    }

    Sidebar.ts

    /**
     * @param { number } id Unique value
     * @param { string } hashId href Unique value
     * @param { string } title show current title
     * @param { string } routeName page find data
     */
     
    interface GlobalSidebar {
        mainTitle: string,
        mainSidebar: Array<Sidebar>
    }
     
    interface Sidebar {
        id: number,
        hashId: string | number,
        title: string,
        routeName: string,
        children: Array<SidebarItem>,
    }
     
    interface SidebarItem {
        id: number,
        parentId: number,
        hashId: string | number,
        title: string,
    }
     
    export {
        GlobalSidebar,
        Sidebar,
        SidebarItem
    }

    2. Create a new mockjs/index.ts

    import Mock from "mockjs";
    import jsBasicInfo from "./tpl/javaScript/index";
    const requestMethod = &#39;post&#39;;
    const BASE_URL = process.env.VUE_APP_BASE_API;
    const mocks = [jsBasicInfo];
     
    for (let i of mocks) {
        Mock.mock(BASE_URL + &#39;/&#39; + i.name, requestMethod, i.jsBasicInfo);
    }
     
    export default Mock

    3. Introduce main.ts

    import { createApp } from &#39;vue&#39;
    import App from &#39;./App.vue&#39;
     
    if(process.env.NODE_ENV == &#39;development&#39;){
        require(&#39;./mockjs/index&#39;)
    }
     
    const app = createApp(App);
    app.mount(&#39;#app&#39;);

    3. Combined use

    is actually the code that just called axios

    <script lang="ts" setup name="Sidebar">
    import { ref, reactive, onBeforeMount } from "vue"
    import { info } from "@/api"
    import { useRoute } from "vue-router"
    const route = useRoute();
     
    let loading = ref<boolean>(false);
    let sidebar = ref<any>({});
     
    const _fetch = async (): Promise<void> => {
        const routeName = route.name as string;
        const path = &#39;/&#39; + routeName.replace(routeName[0], routeName[0].toLocaleLowerCase()) + &#39;Info&#39;
        try {
            loading.value = true;
            const res = await info({ path, routeName });
            if (!res || !res.data) return;
            sidebar.value = res.data;
        } finally {
            loading.value = false
        }
    }
     
    onBeforeMount(() => {
        _fetch();
    })
     
    </script>

    The above is the detailed content of What is the method of encapsulating axios and using mock.js with vue3 and ts?. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    分享两个可以绘制 Flowable 流程图的Vue前端库分享两个可以绘制 Flowable 流程图的Vue前端库Sep 07, 2022 pm 07:59 PM

    前端有没有现成的库,可以直接用来绘制 Flowable 流程图的?下面本篇文章就跟小伙伴们介绍一下这两个可以绘制 Flowable 流程图的前端库。

    vue是前端css框架吗vue是前端css框架吗Aug 26, 2022 pm 07:37 PM

    vue不是前端css框架,而是前端JavaScript框架。Vue是一套用于构建用户界面的渐进式JS框架,是基于MVVM设计模式的前端框架,且专注于View层。Vue.js的优点:1、体积小;2、基于虚拟DOM,有更高的运行效率;3、双向数据绑定,让开发者不用再去操作DOM对象,把更多的精力投入到业务逻辑上;4、生态丰富、学习成本低。

    聊聊Vue3+qrcodejs如何生成二维码并添加文字描述聊聊Vue3+qrcodejs如何生成二维码并添加文字描述Aug 02, 2022 pm 09:19 PM

    Vue3如何更好地使用qrcodejs生成二维码并添加文字描述?下面本篇文章给大家介绍一下Vue3+qrcodejs生成二维码并添加文字描述,希望对大家有所帮助。

    手把手带你利用vue3.x绘制流程图手把手带你利用vue3.x绘制流程图Jun 08, 2022 am 11:57 AM

    利用vue3.x怎么绘制流程图?下面本篇文章给大家分享基于 vue3.x 的流程图绘制方法,希望对大家有所帮助!

    一文深入详解Vue路由:vue-router一文深入详解Vue路由:vue-routerSep 01, 2022 pm 07:43 PM

    本篇文章带大家详解Vue全家桶中的Vue-Router,了解一下路由的相关知识,希望对大家有所帮助!

    手把手带你使用Vue开发一个五子棋小游戏!手把手带你使用Vue开发一个五子棋小游戏!Jun 22, 2022 pm 03:44 PM

    本篇文章带大家利用Vue基础语法来写一个五子棋小游戏,希望对大家有所帮助!

    手把手带你了解VUE响应式原理手把手带你了解VUE响应式原理Aug 26, 2022 pm 08:41 PM

    本篇文章我们来了解 Vue2.X 响应式原理,然后我们来实现一个 vue 响应式原理(写的内容简单)实现步骤和注释写的很清晰,大家有兴趣可以耐心观看,希望对大家有所帮助!

    通过9个Vue3 组件库,看看聊前端的流行趋势!通过9个Vue3 组件库,看看聊前端的流行趋势!May 07, 2022 am 11:31 AM

    本篇文章给大家分享9个开源的 Vue3 组件库,通过它们聊聊发现的前端的流行趋势,希望对大家有所帮助!

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    Repo: How To Revive Teammates
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    Hello Kitty Island Adventure: How To Get Giant Seeds
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.