這個(gè)小節(jié)里,我們要通過和后端數(shù)據(jù)交互實(shí)現(xiàn)一個(gè)登錄的功能。
這里我們要用到vue-resource苔咪,vue-resouce就相當(dāng)于jQuery的$.ajax锰悼,是用來訪問后端數(shù)據(jù)的。
安裝
npm install vue-resource
簡(jiǎn)單調(diào)用
在main.js中引用vue-resource
import VueResource from 'vue-resource'
Vue.use(VueResource)
在Login.vue中改寫login方法
login:function(){
this.$http.get('http://*****/authenticate/credentials'
,{
params:{
UserName : this.username,
Password : this.password
}
})
.then(
response => {
this.message = '';
router.push({path:'/main'});
}
,response =>{
this.message = '用戶名或密碼錯(cuò)誤';
}
);
}
可以看到我們使用了this.$http.get方法团赏,我們傳了兩個(gè)參數(shù)url和params箕般,分別是API的地址和參數(shù)。then方法的參數(shù)是兩個(gè)函數(shù)舔清,第一個(gè)是訪問成功的回調(diào)函數(shù)丝里,第二個(gè)是訪問失敗的回調(diào)函數(shù)。
具體可參考官方文檔
全局root url
url每次都帶上長(zhǎng)長(zhǎng)的根路徑http://*****
体谒,確實(shí)很煩人杯聚,我們?cè)谌种信渲靡幌隆?br>
在main.js中
Vue.use(VueResource);
Vue.http.options.root = 'http://****';
然后在login方法中
this.$http.get('authenticate/credentials')
這里面有一個(gè)tricky的地方,正確的是authenticate/credentials
抒痒,而不是/authenticate/credentials
幌绍,多了個(gè)/
會(huì)變成網(wǎng)站個(gè)根目錄,也就是'http://localhost:8080'故响。
開發(fā)和生產(chǎn)環(huán)境
我們的開發(fā)環(huán)境API和生產(chǎn)環(huán)境API往往是分開的傀广。我們下面用webpack給開發(fā)環(huán)境和生產(chǎn)環(huán)境配置不同的接口地址。
首先我們找到下面的文件:
/config/dev.env.js
/config/prod.env.js
這兩個(gè)文件就是針對(duì)開發(fā)環(huán)境和生產(chǎn)環(huán)境設(shè)置不同參數(shù)的文件彩届。
我們先打開dev.env.js伪冰,修改一下開發(fā)環(huán)境的配置。在module.exports加入一行
API_ROOT: '"http://***"'
類似的我們?cè)傩薷囊幌聀rod.env.js樟蠕。
在main.js中調(diào)用設(shè)置好的參數(shù)贮聂。
Vue.http.options.root = process.env.API_ROOT