vue项目使用mock.js

开发vue项目时有时候后端没办法那么快提供接口,那我们只能用mock.js自己提前模拟接口,请求数据。

1、安装vue项目

1)cnpm i -g vue-cli //安装全局vue-cli脚手架
2)vue init webpack vueAxios(项目文件夹名)
3)cd vueAxios(项目名)
4)cnpm i

2、安装axios

1)cnpm i axios 或者  淘宝镜像: cnpm i axios
2)src =》main.js里面引入安装好的axios:import axios from 'axios'
3)把axios挂载在vue原型上:Vue.prototype.$axios = axios;

3、安装mock.js

1)cnpm i mockjs --save-dev
2)src =》main.js里面引入安装好的mock:import './mock/mock.js'

4、在main.js最下面配置axios的请求拦截

//创建axios实例 
var instance = axios.create();
//instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
//instance.defaults.widthCredentials = true;
instance.baseURL = 'http://localhost:8080';
//instance.defaults.timeout = 1000*10;

// 将axios挂载到Vue实例,在组件中可以直接使用

// 添加请求拦截器
instance.interceptors.request.use(
  config => {
  alert(1);
  tip('请求成功');    
  return config;
}, error => {
  tip('请求失败');    
  return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use(response => {
  tip('响应成功');
  return response;
}, error => {
  const { response } = error;
  //errorHandle(response.status, response.data.message);
  return Promise.reject(response);
});

5、新建的mock.js文件里写接口请求返回的数据:新建文件夹mock,和在新建文件夹mock下面新建mock.js,并写接口请求返回的数据。此mock.js文件代码如下:

import Mock from 'mockjs'

const Random = Mock.Random

// mock需要给三个参数,url(与axios请求是传的url一致,我这个是本地启动的项目就直接用本地域名了)
// 请求类型: get post...其他看文档
// 数据处理函数,函数需要return数据
Mock.mock('http://localhost:8080/test/city', 'get', () => {
  let citys = []
  for (let i = 0; i < 10; i++) {
    let obj = {
      id: i+1,
      city: Random.city(),
      color: Random.color()
    }
    citys.push(obj)
  }
  return {
    cityList:citys
  }
})
// post请求,带参数,参数会在data中返回,会返回url,type,body三个参数,可以把data打印出来看看
Mock.mock('http://localhost:8080/test/cityInfo', 'post', (data) => {
  // 请求传过来的参数在body中,传回的是json字符串,需要转义一下
  const info= JSON.parse(data.body)
  let list = {}
      list.img = Random.image('200x100', '#4A7BF7', info.name);
  return {
    img: Random.image('200x100', '#4A7BF7', info.name)
  }
})

6、HelloWorld页面请求mock.js里写的接口,如下:

<template>
  <div>
    test
    <button @click="clickMe">获取城市</button>
    <ul class="city_container">
      <li class="city_item" v-for="item in cityList" :key="item.id">
        <a href="javascript:void(0)" :style="{color: item.color}">{{item.city}}</a>
      </li>
    </ul>
  </div>
</template>
<script>
  export default {
    name: 'test',
    components: {

    },
    data() {
      return {
        cityList: [],
        img: ''
      }
    },
    methods: {
      clickMe () {// 这里请求的地址要和mock中定义的请求地址一致
        this.$axios.get('http://localhost:8080/test/city').then(res => {
          console.log(77, res)
          if (res.data) {
            this.cityList = res.data.cityList
          }
        })
      }
    }

  }
</script>
<style scoped>
.city_item {
  list-style: none;
  float: left;
  border: 1px solid orange;
   auto;
  height: 50px;
  line-height: 50px;
  padding: 0 5px;
  border-right: none;
}
.city_container :last-of-type {
  border-right: 1px solid orange;
}
.city_container .city_item a {
  text-decoration: none;
  border: none;
}
</style>

  

 

原文地址:https://www.cnblogs.com/zzwlong/p/13468984.html