Use of mockjs

Use of mockjs

Concept: send requests for self-entertainment, because the mock stores data by itself, and then sends requests to read data from the mock. Sending requests is still consistent with ajax. Just install the following tutorial, no need to cross domains and deal with http domain name prefixes at all!

Install:npm i mockjs -D

1. Create a mock folder to store json data and mockServe.js (json data: simulated by yourself, not obtained from the server)

banner.json: (carousel image data)

[
  {
    
    
    "id": "1",
    "imgUrl": "/images/banner1.jpg"
  },
  {
    
    
    "id": "2",
    "imgUrl": "/images/banner2.jpg"
  },
  {
    
    
    "id": "3",
    "imgUrl": "/images/banner3.jpg"
  },
  {
    
    
    "id": "4",
    "imgUrl": "/images/banner4.jpg"
  }
]

2. mockServe.js: mock the server, set the response body, and use the data written by yourself

import Mock from 'mockjs'

// 引入 json 数据
import banner from './banner.json'

// 设置响应
Mock.mock('/mock/banner',{
    
    
    data: banner,    
})

3. Go to main.js to activate the mock service

import '@/mock/mockServe'

4. In the mock folder, create a new mockRequests.js

mockRequests.js

// mockRequests:mock 的 ajax 封装

import axios from 'axios';

// 进度条
import nprogress from 'nprogress'
import 'nprogress/nprogress.css';

const mockRequests = axios.create({
    
    

    //基础路径 请求url默认开头会加上baseURL
    baseURL: "/mock",
    
    //请求不能超过5S
    timeout: 5000,

});

//请求拦截器----在项目中发请求前执行的函数
mockRequests.interceptors.request.use(function(config) {
    
    

    // 加载进度条
    nprogress.start();

    return config;
})

//响应拦截器----当服务器响应请求后的回调函数
mockRequests.interceptors.response.use(
    // 成功回调
    function(res) {
    
    
        // 进度条结束
        nprogress.done();

        // 直接返回响应体的 data 作为 promise对象 的value
        return res.data
    },

    // 失败回调
    function(err) {
    
    
        nprogress.done();

        console.log('mock数据请求失败');
        return err;
    }
)

export default mockRequests;

5. Enter api/index.js and write mock request function

import mockRequests from './mockRequests'

// mock 接口
export const reqgetBannerList = function() {
    
    
    return mockRequests.get('/banner');
}

6. Finally! Send a mock request in the component, such as calling the reqgetBannerList function

import {
    
     reqgetBannerList } from '@/api'

async updataBannerList(context) {
    
    
    let result = await reqgetBannerList();

    if(result) {
    
    
        console.log(result.data)
    }
}

Guess you like

Origin blog.csdn.net/m0_63907100/article/details/129413092