一、創(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í)行成功后會提示已經(jīng)啟動了一個端口為3000的服務(wù),在瀏覽器中輸入localhost:3000 能看到如下的頁面:
點擊 'user' 就能看到我們定義的數(shù)據(jù)信息
到此,本地Mock Server 已經(jīng)搭建完成
四、向本地Server請求數(shù)據(jù)
在項目中如何向本地Server請求數(shù)據(jù)呢?
通過webpack的proxy,可以將本地的Ajax請求代理到Mock Server上
在config/index.js文件中加入如下配置
配置完成啟動 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)容如下:
執(zhí)行 json-server db.js 再次查看 localhost:3000/user 已經(jīng)能看到數(shù)據(jù)效果了
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)搭建完成。