Official: Axios is a promise based HTTP library that can be used in browsers and node.js
Here is English document And found on kancloud Chinese document
Install under the vue project (here is a simple example of using the project created by vue CLI)
$ npm i axios
Enter src/main.js to import axios
import axios from 'axios'
Vue.prototype.axios = axios//Added under the Vue prototype, axios is not a plug-in, unable to use vue.use()
Open components/HelloWorld.vue as follows:
<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))
//Modify the "this" direction. You can change it from bind(this) to ES6 response = > this.books = response.data.title
}
}
}
</script>
Then add a test.json file in the static folder, as follows:
{
"title": "javascript"
}
Go back to the page and click the button to display javascript to indicate that the request is successful (this is not a cross domain).
Next, simply configure it, and try to cross domains with Douban api
Open config/index.js, add and modify as follows
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api':{
target: 'https://api.douban.com/v2/',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
},
Open components/HelloWorld.vue as follows:
<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>
Open the page, let's try to search javascript, as shown below, and list the books (from Douban reading)
That's all.