vue使用mock模拟接口

下载依赖

npm i webpack-api-mocker --save-dev

编写 /mocker/index.js,用于定义mock接口

const proxy = {
  'GET /mock/get/test': {
    errMsg: null,
    code: 200,
    data: {
      id: 1,
      name: '零三',
      url: 'https://web03.cn'
    }
  },
  'POST /mock/post/test': (req, res) => {
    res.send({
      errMsg: null,
      code: 200,
      data: [
        {
          id: 1,
          name: '零三',
          url: 'https://web03.cn'
        },
        {
          id: 2,
          name: '零零三',
          url: 'https://web03.cn'
        }
      ]
    });
  },
  'GET /mock/error/test': {
    errMsg: '服务器异常,请稍后再试',
    code: 500,
    data: null
  }
}
module.exports = proxy

vue.config.js新增配置

const path = require('path')
const apiMocker = require('webpack-api-mocker')
module.exports = {
  devServer: {
    before(app) {
	//以下路径为自己创建的接口文件所在路径
      apiMocker(app, path.resolve('./src/mocker/index.js'), {
        changeHost: true
      })
    }
  }
}

使用

axios我挂到vue原型里面,所以是this.axios

    getUserList(){
      this.axios.post('/mock/post/test')
        .then(res => {
          console.log(res)
          this.userList = res.data.data
        })
    },
    getUserInfo(){
      this.axios.get('/mock/get/test')
        .then(res => {
          console.log(res)
          this.userInfo = res.data.data
        })
    },
    errorTest(){
      this.axios.get('/mock/error/test')
        .then(res => {
          console.log(res)
        })
    }


详见脚手架:https://gitee.com/yuan30/mobile_end_scaffold

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值