從頭搭建Vue + axios + Mock Server的開發(fā)環(huán)境

一、創(chuàng)建項目


使用vue開發(fā)項目時,通過腳手架工具vue-cli可以很方便的構(gòu)建項目,熱重載、保存時靜態(tài)檢查以及可用于生產(chǎn)環(huán)境的構(gòu)建配置都一并創(chuàng)建好。

# 全局安裝 vue-cli

$ npm install -g vue-cli

# 創(chuàng)建一個基于 webpack 模板的新項目

$ vue init webpack my-project

# 安裝依賴

$ cd my-project

$ npm install

更具體的可以看官方文檔:http://cn.vuejs.org/v2/guide/installation.html

二、安裝網(wǎng)絡(luò)請求模塊


vue2.0后官方不再推薦vue-resource 作為 ajax 方案。(具體原因看這:https://github.com/vuefe/vuefe.github.io/issues/186)?

在這里使用axios處理ajax請求,對應(yīng)的vue插件:vue-axios

# 安裝 axios 和 vue-axios

$ npm install --save axios vue-axios

# 在main.js中引入

import axios from 'axios'

import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)

# 在組件中使用axios

this.axios.get('/api/user').then((response) => {

? ? console.log(response.data)

}).catch((error) => {

? ? console.error(error)

})

axios更詳細(xì)的使用方法看這里:https://github.com/mzabriskie/axios

三、Json-Server


項目搭建好了,需要本地模擬數(shù)據(jù)來測試接口效果。

這里的思路是啟動一個本地Server來處理請求返回模擬數(shù)據(jù),項目中通過webpack的proxy代理過去。

這里使用Json-Server這個工具來構(gòu)建本地Server

# 安裝Json-Server

$ npm install -g json-server

安裝完成后,在項目中創(chuàng)建db.json文件模擬返回的數(shù)據(jù)內(nèi)容。

{

? ? "user": {

? ? ? ? "name" : "Sugar",

? ? ? ? "age" : 22,

? ? ? ? "sex" : "girl"

? ? }

}

然后執(zhí)行 json-server db.json

執(zhí)行結(jié)果

執(zhí)行成功后會提示已經(jīng)啟動了一個端口為3000的服務(wù),在瀏覽器中輸入localhost:3000 能看到如下的頁面:

localhost:3000

點擊 'user' 就能看到我們定義的數(shù)據(jù)信息

user 接口

到此,本地Mock Server 已經(jīng)搭建完成

四、向本地Server請求數(shù)據(jù)


在項目中如何向本地Server請求數(shù)據(jù)呢?

通過webpack的proxy,可以將本地的Ajax請求代理到Mock Server上

在config/index.js文件中加入如下配置

proxy配置

配置完成啟動 npm run dev 進行測試吧。

更多proxy配置信息,請參考以下相關(guān)資料:

https://vuejs-templates.github.io/webpack/proxy.html

http://webpack.github.io/docs/webpack-dev-server.html#proxy

五、使用Mock.js


Mock Server中 db.json 中的數(shù)據(jù)是是死的,我們可以借助 Mock.js 生成動態(tài)數(shù)據(jù),增加測試的真實性。

# 安裝mock.js

npm install mockjs --save-dev

項目中創(chuàng)建mock/ db.js 文件,內(nèi)容如下:

db.js

執(zhí)行 json-server db.js 再次查看 localhost:3000/user 已經(jīng)能看到數(shù)據(jù)效果了

localhost:3000/user

Mock.js的詳細(xì)用法參考:http://mockjs.com/examples.html

六、整合


項目開發(fā)時,分別要輸入兩條命令比較麻煩。

我們在package.json中配置一條mockdev命令 ,以方便開發(fā)。

在 scripts 里加入如下兩條配置:

"mock": "node_modules/.bin/json-server --watch mock/db.js --port 3000",

"mockdev": "npm run mock & npm run dev"

到此 vue + axios + mock server的環(huán)境已經(jīng)搭建完成。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容