1、axios简介
2、axios安装
npm install --save axios
//用于将post请求中的data对象转化为字符串
npm install --save querystring
3、axios使用
在要进行网络请求的组件中进行导入:
import axios from ‘axios’
比如在MyCustomComponent.vue文件中进行导入使用:
<template>
<div>
<p>{{ chengpin.title }}</p>
</div>
</template>
<script>
import axios from "axios"
import querystring from "querystring"
export default {
name: "MyCustomComponent",
data() {
return {
chengpin: {}
}
},
mounted() {
// get请求方式
axios({
method: "get",
url: "http://iwenwiki.com/api/blueberrypai/getChengpinDetails.php"
}).then(res => {
this.chengpin = res.data.chengpinDetails[0];
})
// 快捷get请求
axios.get("http://iwenwiki.com/api/blueberrypai/getChengpinDetails.php").then(res => {
console.log("--------快捷get请求--------");
console.log(res.data);
})
// post请求方式
axios({
method: "post",
url: "http://iwenwiki.com/api/blueberrypai/login.php",
data: querystring.stringify({
user_id: "iwen@qq.com",
password: "iwen123",
verification_code: "crfvw"
})
}).then(res => {
console.log("--------post请求方式--------");
console.log(res.data);
})
// 快捷post请求
axios.post("http://iwenwiki.com/api/blueberrypai/login.php", querystring.stringify({
user_id: "iwen@qq.com",
password: "iwen123",
verification_code: "crfvw"
})
).then(res => {
console.log("--------快捷post请求--------");
console.log(res.data);
})
}
}
</script>
<style scoped>
</style>
App.vue
<template>
<MyComponent/>
</template>
<script>
import MyComponent from './components/MyCustomComponent.vue'
export default {
name: 'App',
data(){
return {
}
},
components: {
MyComponent
}
}
</script>
<style>
*{
margin: 0px;
padding: 0px;
}
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
</style>
效果: