目錄
1、爲何官方推薦使用axios而不用vue-resource
附件:
跨域的webpack配置devServer.proxy
◆ 參考文檔
➊ 配置
➋ 到具體頁面中的應用
➌ 如何中斷(取消)axios
的請求
-
【vue學習】axios(重要)
◆ 問題
1、爲何官方推薦使用axios
而不用vue-resource
在Vue1.x
中,官方推薦使用的ajax
庫是vue-resource。到了Vue2.x
,官方(尤大)推薦的ajax
庫改爲了Axios
,按照說法是因爲已有一個更完備的輪子,就不需要造一個新的。
2、如何解決跨域請求
◆ axios實戰
-
1 使用教程
npm install axios
- 2 main.js 引用
import axios from 'axios'
/* 添加到prototype,所有的vue實例都可以使用(/具有)這個對象/方法 */
Vue.prototype.$axios = axios
- 3 script中實際獲取數據
<!-- content.vue -->
<template>
<div id="app">
大家好
<p v-model="info"></p>
</div>
</template>
<script>
export default {
data() {
return {
info: null
}
},
methods: {
getCnjc() {
this.$axios
.get('https://www.runoob.com/try/ajax/json_demo.json')
.then(response => {
console.log(response)
this.info = response
})
.catch(function(error) { // 請求失敗處理
console.log(error);
});
}
},
mounted() {
this.getCnjc()
}
}
</script>
<style scoped lang="stylus" rel="stylesheet/stylus">
@import "~common/stylus/variable.styl"
/* #app {
font-size: $font-size-medium;
color: $color-theme;
} */
body {
font-size: 50px;
color: ffcd32;
}
</style>
- 4 請求菜鳥教程地址遇到跨域
♨ 如何解決跨域問題呢?
答:你不可能每一次/user /info去配置跨域,所以如果是/api開頭,允許跨域,並且重新配置pathRewrite,將api開頭的替換成‘’字符串,
- 1 ../config/index.js
proxyTable: {
'/api': {
target: 'https://www.runoob.com', //你要訪問的服務器域名
changeOrigin: true, //允許跨域
pathRewrite: {
'^/api': '/'
}
}
},
- 2 script使用
<script>
export default {
data() {
return {
info: null
}
},
methods: {
getCnjc() {
this.$axios
// .get('https://www.runoob.com/try/ajax/json_demo.json')
.get('/api/try/ajax/json_demo.json') // 原先請求地址變成這個,如果是try開頭的則允許跨域
.then(response => {
console.log(response)
this.info = response
})
.catch(function(error) { // 請求失敗處理
console.log(error);
});
}
},
mounted() {
this.getCnjc()
}
}
</script>
- 3 最終結果
5 這個demo有用到stylus
6
7
8
9
10