vue中的mock
安装mockjs
npm install mockjs --save
编写mock.js
import Mock from 'mockjs' //引入mockjs import apiData from './data.json'//引入json格式的数据 Mock.mock('/seller', {code:0, data:apiData.seller})//定义接口 Mock.mock('/goods', {code:0, data:apiData.goods}) Mock.mock('/ratings', {code:0, data:apiData.ratings})
mian.js引入
import './Mock/Mock' //加载mockjs
api/index.js 定义请求
export const reqShopInfo = () => ajax('/shop_info') /** * 获取商家评价数组 */ export const reqShopRatings = () => ajax('/shop_ratings') /** * 获取商家商品数组 */ export const reqShopGoods = () => ajax('/shop_goods')
VUEX:
state:
export default { goods: [], // 商品列表 ratings: [], // 商家评价列表 info: {}, // 商家信息 }
mutation-types
export const RECEIVE_GOODS = 'receive_goods' // 接收商品数组 export const RECEIVE_RATINGS = 'receive_ratings' // 接收商家评价数组 export const RECEIVE_INFO = 'receive_info' // 接收商家信息
mutation
[RECEIVE_INFO](state, {info}) { state.info = info }, [RECEIVE_RATINGS](state, {ratings}) { state.ratings = ratings }, [RECEIVE_GOODS](state, {goods}) { state.goods = goods },
actions
// 异步获取商家信息 async getShopInfo({commit}, cb) { const result = await reqShopInfo() if(result.code===0) { const info = result.data info.score = 3.5 commit(RECEIVE_INFO, {info}) cb && cb() } }, // 异步获取商家评价列表 async getShopRatings({commit}, cb) { const result = await reqShopRatings() if(result.code===0) { const ratings = result.data commit(RECEIVE_RATINGS, {ratings}) cb && cb() } }, // 异步获取商家商品列表 async getShopGoods({commit}, cb) { const result = await reqShopGoods() if(result.code===0) { const goods = result.data commit(RECEIVE_GOODS, {goods}) // 如果组件中传递了接收消息的回调函数, 数据更新后, 调用回调通知调用的组件 cb && cb() } },