Bootstrap

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)
        })
    }

;