目录
1、为何官方推荐使用axios而不用vue-resource
◆ 参考文档
➊ 配置
➋ 到具体页面中的应用
➌ 如何中断(取消)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 请求菜鸟教程地址遇到跨域
♨ 如何解决跨域问题呢?
答:
- 1 ../config/index.js
proxyTable: {
'/try': {
target: 'https://www.runoob.com', //你要访问的服务器域名
changeOrigin: true, //允许跨域
pathRewrite: {
'^/try': '/try'
}
}
},
- 2 script使用
<script>
export default {
data() {
return {
info: null
}
},
methods: {
getCnjc() {
this.$axios
// .get('https://www.runoob.com/try/ajax/json_demo.json')
.get('/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