vue请求数据及安装使用axios教程
七娃博客580人阅读
vue安装之后,自身没有请求接口的方法,目前请求数据可以用以下三种插件:vue-resource、axios、fetch-jsonp,我习惯使用axios,下面说一下axios的使用方法。
1.安装:
npm install axios
2.main.js中引入:
import axios from 'axios' Vue.prototype.$axios = axios
3.调用方法
this.$http.get/post(url, data, options).then((response) => { console.log(response) }).catch(function (error) { console.log(error) })
例如调用banner轮播api:
let api = 'http://localhost:3000/banner' this.$axios.get(api).then((response) => { that.bannerFlag = true that.bannerIndex = response.data.banners }).catch(function (error) { that.pageErr = true that.errMsg = error })
当用post请求时,header 设置为 application/x-www-form-urlencoded 时, 你需要使用 qs 来转换 post 数据,需要将这些属性值转化为 JSON 字符串,不然后端接受的的数据将无法解析。
import qs from 'qs' this.$http.post(url, qs.stringify(data), { headers: { 'Content-Type': 'application/x-www-form-urlencoded', } }).then((response) => { console.log(response) })
更多axios详情可以前往官方学习:http://www.axios-js.com/
[…] vue在安装了axios之后(vue请求数据及安装使用axios教程),我们就要调接口数据,一个两个接口的还可以这样写: […]