在用Vue-cli构建的项目里安装并使用Axios发送Ajax请求

最近在项目里需要发送Ajax请求调接口 由于Vue2.0版本后不再更新vue-resource了 遂选择了Axios

一、安装Axios和vue-axios

由于Axios是一个库 而不是插件 因此若要在组件里使用 则需要在每个组件里use() 比较麻烦
vue-axios是一个包装器 用于将Axios集成到Vue上 这样即可通过全局方法Vue.use()使用Axios插件了

npm install --save axios vue-axios

二、配置

1、引入Axios:
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)
2、将Axios挂载到Vue上:
Vue.prototype.$axios = axios;

三、使用

在组件里使用时 用this.$axios调用Axios即可:

this.$axios.get("localhost:8080/getData").then((response) => {
	console.log(response.data)
})
this.$axios.post("localhost:8080/login", {
                    username: "xxx",
                    password: "yyy"
                }{headers: { "Content-Type": "application/x-www-form-urlencoded"}})
                .then(function (response) {
                    console.log(response);
                })
                .catch(function (error) {
                    console.log(error);
                });

原创文章 252 获赞 42 访问量 214万+

猜你喜欢

转载自blog.csdn.net/Piconjo/article/details/106103285