vue项目内封装axios.,使用Mock,搭建前后端分离环境。Axios + Promise + Mock

1.安装Mock

npm install mockjs --save-dev
1.1加入相关Mock代码

在SRC目录下创建文件夹mock,在里面创建虚拟接口地址及数据:

// mock/index.js
import Mock from "mockjs"; // 引入mockjs
const Random = Mock.Random; // Mock.Random 是一个工具类,用于生成各种随机数据
let data = []; // 用于接受生成数据的数组
for (let i = 0; i < 10; i++) {
    
    
  // 可自定义生成的个数
  let template = {
    
    
    name: Random.name(), // 生成地址,
    string: Random.string(2, 10), // 生成2到10个字符之间的字符串
    date: Random.date() // 生成一个随机日期,可加参数定义日期格式
  };
  data.push(template);
}
Mock.mock("/data/index", "post", data); // 根据数据模板生成模拟数据

2.安装Axios

npm install axios --save
2.1加入相关代码

在SRC目录下创建文件axios.js,在里面设置:请求头、请求拦截、响应拦截:

// axios.js  
import axios from "axios";
axios.defaults.headers.post["Content-Type"] =
 "application/x-www-form-urlencoded";
// 请求拦截器
axios.interceptors.request.use(
 function(config) {
    
    
   return config;
 },
 function(error) {
    
    
   return Promise.reject(error);
 }
);
// 响应拦截器
axios.interceptors.response.use(
 function(response) {
    
    
   return response;
 },
 function(error) {
    
    
   return Promise.reject(error);
 }
);

3.最后封装Axios

在SRC目录下创建文件夹services,在内创建文件global.js,内容如下:

//services/global.js"
import axios from "axios";
// 封装axios的post请求
export function fetch(url, params) {
    
    
  return new Promise((resolve, reject) => {
    
    
    axios
      .post(url, params)
      .then(response => {
    
    
        resolve(response.data);
      })
      .catch(error => {
    
    
        reject(error);
      });
  });
}
export default {
    
    
  mockdata(url, params) {
    
    
    return fetch(url, params);
  }
};

4.最后在入口文件main.js添加

import "./mock/index";    
import api from "@/services/global.js";
Vue.prototype.$http = api

5.最后随意文件内调用

this.$http.mockdata("/data/index").then(res => {
    
    
   console.log(res);
}); 

6.最后输入结果:

(10) [{
    
    }, {
    
    }, {
    
    }, {
    
    }, {
    
    }, {
    
    }, {
    
    }, {
    
    }, {
    
    }, {
    
    }]
0: {
    
    name: "Sarah Rodriguez", string: "H1o4NE#kAX", date: "1972-09-13"}
1: {
    
    name: "Karen Miller", string: "oQ@YQ24", date: "1978-10-16"}
2: {
    
    name: "Patricia Thomas", string: "f#gZ", date: "1970-08-29"}
3: {
    
    name: "Eric Allen", string: "Upr%Cop^L", date: "1999-11-25"}
4: {
    
    name: "William Taylor", string: "2[Ir", date: "2018-11-18"}
5: {
    
    name: "Edward Clark", string: "YTBNX!", date: "2016-10-11"}
6: {
    
    name: "Kimberly Gonzalez", string: "lL1&yF", date: "2011-07-23"}
7: {
    
    name: "Laura Davis", string: "X)7Hk", date: "2008-04-14"}
8: {
    
    name: "Dorothy Williams", string: "[w", date: "1999-09-16"}
9: {
    
    name: "David Brown", string: "dAftU1(n", date: "1979-12-12"}
length: 10
__proto__: Array(0)

看到此处的你赶紧试下哈。

本文作为学习用途,原文地址:https://blog.csdn.net/qq_38502227/article/details/102587251

猜你喜欢

转载自blog.csdn.net/qq_39453402/article/details/106258745
今日推荐