1.安裝axios
在項目目錄下安裝,命令:
npm install --save axios vue-axios
2.axios的配置
方法1:在入口main.js中導入axios 並將axios寫入vue的原型,這樣就能更簡單的使用
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
方法二:如果需配置全局axios訪問的路由前綴,可以配置如下內容:
1 import axios from 'axios' 2 const ajax = axios.create({ 3 baseURL: 'http://127.0.0.1:8000' // 配置請求路由前綴 4 }) 5 Vue.config.productionTip = false 6 // Vue.prototype.$ajax = ajax 兩種定義都可以,使用時調用對應的變量 7 Vue.prototype.axios = ajax
3. axios.get()方法
3.1 無參情況
axios封裝了get方法,傳入請求地址和請求參數即可。 then中返回的是正常情況下的數據,而catch中返回的是錯誤信息。請求格式為: this.axios.get(url).then(res => {}).catch(err => {})
import axios from 'axios'
const ajax = axios.create({
baseURL: 'http://127.0.0.1:8000' // 配置請求路由前綴
})
Vue.config.productionTip = false
// Vue.prototype.$ajax = ajax 兩種定義都可以,使用時調用對應的變量
Vue.prototype.axios = ajax
響應數據形式:
res.data.data : 就是我們后端自己返回的數據
3.2 有參情況
axios封裝了get方法,get方法可以接收請求參數,請求參數定義在格式為: this.axios.get(url, { params }).then(res => {}).catch(err => {})
<script> export default { mounted: function () { var url = 'http://127.0.0.1:8000/api/article/article/' var params = { //要么定義為params 傳參{params}, 使用其他變量名,傳參需{params:其他名} is_delete: 1 } // 傳參數:只能解析params //注意1:傳遞的參數定義為params時,this.axios.get(url,{params}) //注意2: 傳遞的參數定義為searchData時,this.axios.get(url,{params:searData}) this.axios.get(url, { params }) .then(res => { console.log(res.data) }) .catch(err => { alert(err) }) } } </script>
4. axios.post()方法
axios封裝了post方法,post方法可以接收請求參數,請求參數定義在格式為: this.axios.post(url, params).then(res => {}).catch(err => {})
export default { mounted: function () { var url = 'http://127.0.0.1:8000/api/article/article/' var params = { title: '1213', desc: '321' } //post傳參:參數params不需要{} this.axios.post(url, params) .then(res => { console.log(res.data) }) .catch(err => { alert(err) }) } } </script>
5. axios經典寫法
axios的經典寫法,post請求格式為: this.axios({method: 'post',url: url,data: params}).then(res => {}).catch(err => {})
<script> export default { mounted: function () { var url = 'http://127.0.0.1:8000/api/article/article/' var params = { title: '121322', desc: '321' } this.axios({ method: 'post', url: url, data: params }).then(res => { console.log('成功') }).catch(err => { console.log('失敗') }) } } </script>