文章字数:151,阅读全文大约需要1分钟
vue中使用axios进行一步http访问
引入
main.js中
1 2 3 4
| import axios from 'axios' import VueAxios from 'vue-axios'
Vue.use(VueAxios,axios);
|
使用
1 2 3 4 5 6 7
| getMess(){ this.axios.get('api/getNewsList').then((response)=>{ this.newsList=response.data.data; }).catch((response)=>{ console.log(response); }) }
|
GET
1 2 3 4 5 6 7 8 9 10 11
| this.axios.get('/user', {//url params: {//数据 id: 123 } }) .then(function (response) { console.log(response);//成功结果 }) .catch(function (error) { console.log(error);//失败信息 });
|
#POST
1 2 3 4 5 6 7 8 9 10
| this.axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
|
并发请求
1 2 3 4 5 6 7 8 9 10 11 12
| function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } this.axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms) { //两个请求现已完成 }));
|
this指向
原本vue里this指向vue,但是axios里不是,所以会导致this内容报空。可以在method调用axios的函数开头加上let that=this
,然后使用that代替this。