Vue& 使用axios的多种方式

vue中使用axios的多种方式

axios
axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端

它本身具有以下特征:

  • 从浏览器中创建 XMLHttpRequest
  • 从 node.js 发出 http 请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求和响应数据
  • 取消请求
  • 自动转换JSON数据
  • 客户端支持防止 CSRF/XSRF

axios默认是不让ajax请求头部携带cookie的

axios 解决跨域cookie丢失问题

设置 axios.defaults.withCredentials = true 即可

1
2
3
4
5
6
7
8
9
10
11
axios.defaults.withCredentials = true;
var param = new URLSearchParams();
param.append("vCode",vcode);
axios.post('http://localhost',param)
.then(function(res) {
var rs=res.data;
console.log(rs.data);
})
.catch(function(err) {
console.log(err);
});

配合vue

目前主流的 Vue 项目,都选择 axios 来完成 ajax 请求

Axios 是一个基于 promise 的 HTTP 库

axios并没有install 方法,所以是不能使用vue.use()方法的。
那么难道每个文件都要来引用一次?解决方法有很多种:

  1. 结合 vue-axios使用

  2. axios 改写为 Vue 的原型属性

  3. 结合 Vuex的action

结合 vue-axios使用

vue-axios

用于将axios集成到Vuejs的小包装器

github: https://github.com/axios/axios

安装: npm install –save axios vue-axios

vue-axios是按照vue插件的方式去写的。那么结合vue-axios,就可以去使用vue.use方法了

首先在主入口文件main.js中引用

1
2
3
4
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios,axios);

之后就可以使用了,在组件文件中的methods里去使用了

1
2
3
4
5
6
7
8
9
getNewsList(){
this.axios.get('api/getNewsList').then((response)=>{
this.newsList=response.data.data;
}).catch((response)=>{
console.log(response);
})


},

方法2: axios 改写为 Vue 的原型属性
首先在主入口文件main.js中引用,之后挂在vue的原型链上

1
2
3
4
5
6
7
8
9
10
11
import axios from 'axios'
Vue.prototype.$axios= axios

在组件中使用


this.$axios.get('api/getNewsList').then((response)=>{
this.newsList=response.data.data;
}).catch((response)=>{
console.log(response);
})

方法3:结合vuex(待学)

参考链接简书