第一次尝试mock

第一次尝试mock

参考了众多大佬的文章:
https://www.jianshu.com/p/c5568910e946
https://www.cnblogs.com/zishang91/p/7680569.html
https://blog.csdn.net/zwy15841139493/article/details/100804122

先安装mock
npm install mockjs --save

安装vue-resource插件(Ajax请求)和body-parser模块(mock数据,对post请求的模块)
npm install vue-resource --save (–registry=https://registry.npm.taobao.org --verbose 配置了镜像的可不管)
npm install body-parser --save (–registry=https://registry.npm.taobao.org --verbose 配置了镜像的可不管)

main.js 引入

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
import VueResource from "vue-resource";
import axios from "axios";

Vue.prototype.$axios = axios;

Vue.use(VueResource);

Vue.use(ElementUI);
Vue.config.productionTip = false;
require("../mock/index");

new Vue({
  router,
  render: (h) => h(App),
}).$mount("#app");

创建mock文件 配置mock
在这里插入图片描述
mock/index.js

// 首先引入Mock
const Mock = require("mockjs");

// 设置拦截ajax请求的相应时间
Mock.setup({
  timeout: "200-600",
});

let configArray = [];

// 使用webpack的require.context()遍历所有mock文件
const files = require.context(".", true, /\.js$/);
files.keys().forEach((key) => {
  if (key === "./index.js") return;
  configArray = configArray.concat(files(key).default);
});

// 注册所有的mock服务
configArray.forEach((item) => {
  for (let [path, target] of Object.entries(item)) {
    let protocol = path.split("|");
    Mock.mock(new RegExp("^" + protocol[1]), protocol[0], target);
  }
});

配置模拟data

// 优先级
const order = {
  status: 200,
  message: "success",
  data: [
    {
      value: 1,
      label: "加急",
    },
    {
      value: 2,
      label: "急",
    },
    {
      value: 3,
      label: "优先",
    },
    {
      value: 4,
      label: "一般",
    },
  ],
};
export default { 
  "get|/select/order": order,
};

使用:
页面直接使用axios调用模拟数据

 //优先级
      this.$axios
        .get("/select/order")
        .then((res) => {
          this.options = res.data.data;
        })
        .catch(function(error) {
          console.log(error);
        });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值