vue本身不支持發送AJAX請求,需要使用vue-resource(vue1.0版本)、axios(vue2.0版本)等插件實現。
axios是一個基於Promise的HTTP請求客戶端,用來發送請求,也是vue2.0官方推薦的,同時不再對vue-resource進行更新和維護。
resource請求
import VueResource from 'vue-resource' Vue.use(VueResource) this.$http.get("")
或者
Vue.http.get/post
axios請求
參考:GitHub上axios,查看API文檔
安裝axios並引入
1)npm的方式: $ npm install axios -S
2)bower的方式:$ bower install axios
3)cdn的方式:<script src=”https://unpkg.com/axios/dist/axios.min.js”></script>
import axios from 'axios'
get請求:
// GET request for remote image axios({ method:'get', url:'http://bit.ly/2mTM3nY', responseType:'stream' }) .then(function (response) { response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) });
// Make a request for a user with a given ID axios.get('/user?ID=12345') .then(function (response) { // handle success console.log(response); }) .catch(function (error) { // handle error console.log(error); }) .then(function () { // always executed });
// Optionally the request above could also be done as axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .then(function () { // always executed });
post請求
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
// Send a POST request axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } });
具體的請求配置項,查看文檔:https://github.com/axios/axios#request-config
響應數據
axios.get('/user/12345') .then(function (response) { console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); });
interceptors攔截器
攔截器應用場景總結
發起請求加載loading請求結束關閉loading
攔截request:
設置全局請求為ajax請求
有token值則配置上token值
攔截response:
做一些錯誤處理
跨域請求
使用vue-resource發送跨域請求:vue實戰——vue中發送AJAX請求
methods:{ sendJsonp:function(){ this.$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',
{ params:{ wd:'a' }, jsonp:'cb' }).then(function(res){ console.log(res.data); }); } }
在store.js中封裝http請求的方法
推文:vue中http請求
參考文章:
vue-axios interceptors(攔截器)實際應用
Vue+axios(interceptors) 實現http攔截 + router路由攔截 (雙攔截)+ 請求自帶loading效果