1. 安裝axios
npm install axios
2. 注冊(cè)axios
我們一般會(huì)將服務(wù)端的調(diào)用都作為一個(gè)js文件封裝起來,所以這里創(chuàng)建一個(gè)data.js的文件,在文件中可以如下創(chuàng)建請(qǐng)求
import axios from 'axios'
export const getWiSList = policyNo => {//定義一個(gè)方法調(diào)用,是有參數(shù)的調(diào)用,policyNo是調(diào)用后臺(tái)的參數(shù)名,這個(gè)是個(gè)對(duì)象,所以可以是任意類型
return axios.request({//使用request的方式,這樣可以直接在內(nèi)部config對(duì)應(yīng)的各種方式及參數(shù)信息
url: '/api/wi/getSurMsgByPolicyNo',//請(qǐng)求url
method: 'post',//使用的調(diào)用方法
data: policyNo//數(shù)據(jù)
})
};
為了使用方便,我們一般會(huì)將后端的各個(gè)連接封裝在vue.config.js中,這個(gè)文件需要放在根目錄(與src同級(jí)別的目錄)下才會(huì)被build的時(shí)候掃描到
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8001/avatarma',
changeOrigin: true,//是否開啟跨域請(qǐng)求訪問
pathRewrite: {
'/api': ''//url前綴
}
}
}
},
}
在main.js中添加如下信息
import router from './router'
import axios from 'axios';
Vue.use(axios)
3. 使用
在單獨(dú)的vue文件中的script標(biāo)簽中可以這么使用
import {getData} from '@/api/data.js'
//這里是應(yīng)用上面data.js中定義的請(qǐng)求后臺(tái)的方法,需要應(yīng)用多個(gè)方法可以在{}中使用,隔開
export default{
mounted(){//vue的生命周期函數(shù),代表著頁面初始化的時(shí)候調(diào)用
getData(this.policyNo).then(res=>{
console.log(res.data)//res.data就是返回的信息,這里是任意類型的,這也是javaScript這個(gè)動(dòng)態(tài)語言的好處
})
}
}
99. 基礎(chǔ)的使用方法
Get方法使用
有參數(shù)有返回值
axios.get('http://localhost:8080/xxx/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Post方法使用
axios.post('http://localhost:8080/xxx/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});