使用axios调用mock数据
在开发的时候,由于后端数据未能及时给,但有时候又要模拟某些业务场景,mock就是个很不错的选择。使用mock.js拦截ajax请求就更方便的造取数据。以下分别用vuex、一般情况去调用接口。话不多说,直接上代码!
首先安装 axios mockjs
npm i axios -S
npm i mockjs -S
1.新建request.js文件,封装axios
import axios from "axios"
let url = window.location.origin
const service = axios.create({
baseURL: url,
timeout: 50000
})
/**GET请求 */
service.get = (request) =>
new Promise((resolve, reject) => {
service({
...request,
method: 'get'
})
.then(res => { resolve(res.data) })
.catch(err => { reject(err) })
})
export default service
2.创建mock.js文件,使用mock造测试数据
let Mock = require("mockjs")
const Random = require('mockjs').Random;
/**一级分类 */
export let goodsFirst = Mock.mock(/\/goodsFirst/, "get", {
"data|15": [{
//商品一级分类id
"goodsFirstCategoryId|+1": 1,
//商品分类名称
"goodsFirstCategoryName": "@cword(3)",
//二级分类的总称
"goodsSecondTerm": "@cword(4)",
//一级分类对应二级分类ID
"goodsSecondCategoryId|+1": 100
}]
})
/**二级分类 */
export let goodsSecond = Mock.mock(/\/goodsSecond/, "get", {
"data|15": [{
//二级分类ID
"goodsSecondCategoryId|+1": 100,
"data|5-15": [{
//二级分类名称
"goodsSecondCategoryName": "@first(3-5)",
//二级分类图片
"goodsSecondCategoryImage": Random.image('55x55', "#67bdc5"),
//二级分类对应三级分类的ID
"goodsThirdCategoryId|+1": 1000
}]
}]
})
3.封装接口
import service from "./request"
/**获取一级分类 */
export const goodsFirstList = () =>
service.get({
url: '/goodsFirst'
})
/**获取二级分类 */
export const goodsSecondList = () =>
service.get({
url: '/goodsSecond'
})
4.第一种使用vuex调用接口获取mock数据
import Vue from 'vue'
import Vuex from 'vuex'
import { getGoodsDetailsList } from "@/api/getGoods"
Vue.use(Vuex)
export default new Vuex.Store({
state: {
dataList: [],//请求的所有数据
},
getters: {
dataList: state => state.dataList, //所有的数据
},
mutations: {
getGoods(state, data) {
state.dataList = data
}
},
actions: {
getGoodsList({ commit }) {
const { data } = await getGoodsDetailsList()
console.log(data, 'shuju')
commit('getGoods', res.data.data)
}
},
modules: {
},
})
//然后在需要调接口的地方写 this.$store.dispatch("getGoodsList")
5.第二种一般情况调接口
<template>
<div class="index"></div>
</template>
<script>
import { goodsFirstList } from "@api/api.js"
export default {
data(){
return {
dataList:[]
}
},
methods:{
/**初始化*/
async init(){
const { data } = await goodsFirstList()
this.dataList = data
}
},
created(){
this.init()
}
}
</script>
mock相关语法规范可以去看: https://www.jianshu.com/p/4579f40e6108
mock官网
喜欢的小伙伴欢迎留言~