vue中的axios應用


1. axios請求分類

  • get請求
import axios from 'axios;
axios.get(
  url,//請求地址
{
    params:{}, //請求參數
  }
).then((response)=>{
  return response.data //將數據傳給下一個then,作為下一個then的參數
})
  • post請求
import axios from 'axios';
import Qs from 'qs';

axios.post(url, //請求地址
      Qs.stringify(params) //請求參數
      [,{config}] ) //請求的其他配置
.then((response)=>{
  return response.data //將數據傳給下個then,作為下一個then的參數
})
  • request請求
import axios from 'axios';

axios.request({config})
||
axios({
  url:''//請求地址
  method:'get' | 'post' //請求方式
  params:{} //請求參數

})

 2.axios的使用(以get請求為例)

  • 直接在頁面上使用
//需要發送ajax請求的頁面

import axios from 'axios';
axios.get(url,{
  params:{} //請求參數
})
  • 實例屬性化

 

 1 //在main.js文件中引入axios
 2 
 3 import axios from 'axios';
 4 Vue.prototype.$axios = axios;
 5 
 6 //在需要使用的頁面進行使用
 7 this.$axios.get("url").then(response=>{
 8     //將請求到數據賦值給data倉庫中的變量
 9     this.types = response.data.result;
10 })

 

  • 工具化和模塊化

   - 在src文件夾下創建api文件夾,其中有index.js文件

   - 在index.js文件中引入axios模塊

     - 定義基礎路徑

     - 定義地址

     - 定義方法

     - 導出方法

    - 在main.js文件中引入api,並將方法實例屬性化

         - 在頁面上使用

//引入axios模塊
import axios from 'axios'//定義基礎路徑
axios.defaults.baseURL = process.env.BASE_URL;
//定義地址
const urls = {
    types:"/filmApi/loadTypes.php",
    films:"/filmApi/loadFilms.php",
    film:"/filmApi/loadFilmById.php"
}
//定義方法
const loadTypesData = function(){
    return axios.get(urls.types)
                .then((response)=>{
                    return response.data.result
                });
}
//導出方法
export default {
    loadTypesData
}
//在main.js 中進行原型裝載
import api from './api'
Vue.prototype.$api=api;
//在對應的組件上使用
export default{
    data(){
        return{
            types:[];
        }
    },
    methods:{
        this.$api.loadTypesData()
        .then((response)=>{
            this.types=response,data.result 
        })
    },
    mounted(){
        this.loadData();
    }
}

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM