-
Notifications
You must be signed in to change notification settings - Fork 10.3k
7.将请求方法挂到Vue上
江南一点雨 edited this page Jan 5, 2018
·
7 revisions
由于我对axios进行了封装,因此在每一个需要使用axios的地方,都需要导入相应的请求,略显麻烦,参考https://cn.vuejs.org/v2/guide/plugins.html,我将请求方法挂到Vue上,具体操作如下:
1.在main.js中导入所有的请求方法,如下:
import {getRequest} from './utils/api'
import {postRequest} from './utils/api'
import {deleteRequest} from './utils/api'
import {putRequest} from './utils/api'
2.把它们添加到 Vue.prototype 上,如下:
Vue.prototype.getRequest = getRequest;
Vue.prototype.postRequest = postRequest;
Vue.prototype.deleteRequest = deleteRequest;
Vue.prototype.putRequest = putRequest;
如此之后,以后再需要发送网络请求,就不需要导入api了,直接通过下面这种方式即可:
this.postRequest('/login', {
username: this.loginForm.username,
password: this.loginForm.password
}).then(resp=> {
...
}
});