官方说法:Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中
这里是英文文档和在kancloud上发现的中文文档
在vue项目下进行安装(这里用的是vue-cli创建的项目简单的使用示例)
$ npm i axios
进入src/main.js引入axios
import axios from 'axios'
Vue.prototype.axios = axios//在Vue原型下面添加,axios不是插件,无法使用vue.use()
打开components/HelloWorld.vue 代码如下:
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<button @click="seachbook">seach</button>
<p>{{books}}</p>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome',
books: ''
}
},
methods: {
seachbook: function(){
this.axios.get('./static/test.json').then(function(response){
this.books = response.data.title
}.bind(this))
//修改this指向,可以不写bind(this),可改成ES6的写法 response=>this.books = response.data.title
}
}
}
</script>
然后在static文件夹添加一个test.json文件,内容如下:
{
"title": "javascript"
}
回到页面点击按钮,把javascript显示出来表示请求成功(这里并不是跨域)。
接下来简单的配置一下,用豆瓣的api试试跨域
打开config/index.js,添加修改如下
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api':{
target: 'https://api.douban.com/v2/',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
},
打开components/HelloWorld.vue 代码如下:
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<input type="text" v-model="message" @keyup.enter="seach">
<button @click="seach">seach</button>
<p>{{message}}</p>
<ul>
<li v-for="item in booklist" v-text="item"></li>
</ul>
</div>
</template>
<script>
export default {
name: "HelloWorld",
data() {
return {
message: "",
msg: "HelloWorld",
booklist: []
};
},
methods: {
seach: function() {
// var _this = this
this.axios
.get("/api/book/search?q=" + this.message)
.then(
function(response) {
const bookdata = response.data.books;
bookdata.forEach(function(val) {
this.booklist.push(val.title)
}.bind(this));
}.bind(this)
)
.catch(function(response) {
console.log(response);
});
}
}
};
</script>
打开页面,我们试试搜索一下javascript,可见如下,把书名列了出来(来自豆瓣读书)
就这么多