**
Vue-cli中axios基礎用法
**
在使用axios時
首先安裝axios
1:npm install
2:npm install vue-axios --save
3:npm install qs.js --save //它的作用是能把json格式的直接轉成data所需的格式
安裝成功後
在VUE中main.js中加入這些代碼
import Vue from 'vue'
import qs from 'qs'
import axios from 'axios'
Vue.prototype.$axios = axios //全局註冊,使用方法爲:this.$axios
Vue.prototype.qs = qs //全局註冊,使用方法爲:this.qs
這是就可以再頁面中使用axios
<script>
export default{
data(){
return{
username:'用戶名',
password:'密碼',
}
},
created(){
//POST請求
this.$axios({
method:'POST',
url:'api',
data:this.qs.stringify({ //這裏是發送給後臺的數據
username:this.username,
password:this.password,
})
}).then((response) =>{ //這裏使用了ES6的語法
console.log(response) //請求成功返回的數據
}).catch((error) =>{
console.log(error) //請求失敗返回的數據
})
//GET請求
this.$axios({
method:'GET',
url:'api',
params:{ //這裏是發送給後臺的數據
username:this.username,
password:this.password,
}
}).then((response) =>{ //這裏使用了ES6的語法
console.log(response) //請求成功返回的數據
}).catch((error) =>{
console.log(error) //請求失敗返回的數據
})
}
}
</script>
本文介紹的是axios的基本用法,詳細看官方文檔https://github.com/axios/axios