您当前的位置: 首页 > 

【03】

暂无认证

  • 1浏览

    0关注

    196博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

vue使用mock模拟接口

【03】 发布时间:2020-07-23 15:09:22 ,浏览量:1

下载依赖
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

关注
打赏
1657344724
查看更多评论
立即登录/注册

微信扫码登录

0.0837s