自己寫練手項目的時候常常會遇到一個問題,沒有后台接口,獲取數據總是很麻煩,於是在網上找了下,發現一個挺好用的模擬后台接口數據的工具:mockjs.現在把自己在項目中使用的方法貼出來
先看下項目的目錄,這是用vue-cli生成的一個vue項目,主要是需要配置axios和寫接口數據mock.js
首先需要安裝axios和mockjs
npm i axios mockjs --save

在項目中新建一個config目錄,與src同級,配置axios
./config/axios.js
import axios from 'axios' axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded' // 請求攔截器 axios.interceptors.request.use(function(config) { return config }, function(error) { return Promise.reject(error) }) // 響應攔截器 axios.interceptors.response.use(function(response) { return response }, function(error) { return Promise.reject(error) })
在src文件中新建一個mock目錄.定義接口數據
./src/mock/mock.js
mockjs的文檔提供了很多生成隨機數據的字段,使用Random關鍵字+字段方法名就可以,具體需要什么數據可以查看官網文檔http://mockjs.com/examples.html#Random\.zip\(\)
當然你也可以完全自己寫數據
import Mock from 'mockjs' const Random = Mock.Random // mock需要給三個參數,url(與axios請求是傳的url一致,我這個是本地啟動的項目就直接用本地域名了) // 請求類型: get post...其他看文檔 // 數據處理函數,函數需要return數據 Mock.mock('http://localhost:8081/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:8081/test/cityInfo', 'post', (data) => { // 請求傳過來的參數在body中,傳回的是json字符串,需要轉義一下 const info= JSON.parse(data.body) return { img: Random.image('200x100', '#4A7BF7', info.name) } })
在main.js文件中引入mock和axios
./main.js
import Vue from 'vue' import App from './App.vue' import VueRouter from 'vue-router' import routes from './router' import './mock/mock.js' import axios from 'axios' import '../config/axios' // 將axios掛載到Vue實例,在組件中可以直接使用 Vue.prototype.$axios = axios Vue.config.productionTip = false Vue.use(VueRouter) const router = new VueRouter({ routes, strict: process.env.NODE_ENV !== 'production' }) new Vue({ router, render: h => h(App) }).$mount('#app')
在vue組件中調用接口渲染頁面
<template> <div> test <button @click="clickMe">獲取城市</button> <ul class="city_container"> <li class="city_item" v-for="item in cityList" :key="item.id" @click="getCityInfo(item.city)"> <a href="javascript:void(0)" :style="{color: item.color}">{{item.city}}</a> </li> </ul> <img :src="img" alt=""> </div> </template> <script> export default { name: 'test', components: { }, data() { return { cityList: [], img: '' } }, methods: { clickMe () {
// 這里請求的地址要和mock中定義的請求地址一致 this.$axios.get('http://localhost:8081/test/city').then(res => { console.log(77, res) if (res.data) { this.cityList = res.data.cityList } }) }, getCityInfo (name) { this.$axios.post('http://localhost:8081/test/cityInfo', { name: name }).then(res => { console.log(88, res) if (res.data) { this.img = res.data.img } }) } } } </script> <style scoped> .city_item { list-style: none; float: left; border: 1px solid orange; width: 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>
頁面效果:
獲取隨機城市

點擊城市獲取圖片
