使用第三方模块——axios

目录

◆ 参考文档

Vue.js Ajax(axios) 菜鸟教程

使用说明 · Axios 中文说明 · 看云

Axios源码深度剖析 - AJAX新王者

具体config配置参考

【vue学习】axios(重要)

◆ 问题

1、为何官方推荐使用axios而不用vue-resource

2、如何解决跨域请求

◆ axios实战

1 使用教程

2 main.js 引用

3 script中实际获取数据

4 请求菜鸟教程地址遇到跨域

      ♨ 如何解决跨域问题呢?

5 这个demo有用到stylus

 


◆ 参考文档

      ➊ 配置

      

      ➋ 到具体页面中的应用

      

      ➌ 如何中断(取消)axios的请求

      

      ➍ axios怎么解决跨域的问题

link

◆ 问题

1、为何官方推荐使用axios而不用vue-resource

Vue1.x中,官方推荐使用的ajax库是vue-resource。到了Vue2.x,官方(尤大)推荐的ajax库改为了Axios,按照说法是因为已有一个更完备的轮子,就不需要造一个新的。

2、如何解决跨域请求

     link

◆ axios实战

  1. 1 使用教程

npm install axios
  1. 2 main.js 引用
import axios from 'axios'

/* 添加到prototype,所有的vue实例都可以使用(/具有)这个对象/方法 */
Vue.prototype.$axios = axios
  1. 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>
  1. 4 请求菜鸟教程地址遇到跨域

      ♨ 如何解决跨域问题呢?

答:

  1. 1 ../config/index.js
		proxyTable: {
			'/try': {
				target: 'https://www.runoob.com', //你要访问的服务器域名
				changeOrigin: true, //允许跨域
				pathRewrite: {
					'^/try': '/try'
				}
			}
		},
  1. 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>
  1. 3 最终结果

5 这个demo有用到stylus

请转至此篇文章配置相应依赖

6

7

8

9

10

发布了234 篇原创文章 · 获赞 52 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/Sicily_winner/article/details/104040808