axios is a promise-based HTTP library, similar to jQuery's Ajax, for HTTP requests. Available in browser and node.js.
1. Axios installation:
Use the command:
npm install axios
2. Install qs:
Use the command:
npm install qs
3. Introduce axios and qs [global import]:
Introduce axios and qs in the main.js file, and bind to the prototype of vue.
import Vue from 'vue'
import App from './App.vue'
import router from './router'
Vue.config.productionTip = false;
// 1.引入axios
import axios from 'axios'
// 2.引入qs
import qs from 'qs'
// 3.将axios绑定到vue原型上,并命名为$axios
Vue.prototype.$axios = axios;
// 4.将qs绑定到vue原型上,并命名为$qs
Vue.prototype.$qs = qs;
new Vue({
router,
render: h => h(App),
}).$mount('#app')
Axios basic use
1. Get request
<template>
<div>
<p>{
{ name }}</p>
</div>
</template>
<script>
export default {
name: "Home",
data() {
return {
name: "GET请求"
}
},
created() {
// 1. 第一种写法
this.$axios({
method: 'get',
url: 'http://xxx/webapi/user/info',
params: {
id: 1
}
}).then((res) => {
console.log(res.data);
})
// 2. 使用get别名写法
this.$axios.get('http://xxx/webapi/user/info', {
params: {
id: 1
}
}).then((res) => {
console.log(res.data);
})
}
}
</script>
Two, post request
<template>
<div>
<p>{
{ name }}</p>
</div>
</template>
<script>
export default {
name: "Home",
data() {
return {
name: "POST请求"
}
},
created() {
// 1. 第一种写法
this.$axios({
method: 'post',
url: 'http://xxx/webapi/user/info',
data: {
id: 1
}
}).then((res) => {
console.log(res.data);
})
// 2. 使用post别名写法
this.$axios.post('http://xxx/webapi/user/info', {
id: 1
}).then((res) => {
console.log(res.data);
})
}
}
</script>
Original author: Wu Xiaotang
Creation time: 2023.6.21