vue axios數(shù)據(jù)請求get、post方法及實例詳解
我們常用的有g(shù)et方法以及post方法,下面簡單的介紹一下這兩種請求方法
vue中使用axios方法我們先安裝axios這個方法
npm install --save axios
安裝之后采用按需引入的方法,哪個頁面需要請求數(shù)據(jù)就在哪個頁面里引入一下。
import axios from 'axios'
引入之后我們就可以進行數(shù)據(jù)請求了,在methods中創(chuàng)建一個方法
methods:{
getInfo(){
let url = "url"
axios.get(url).then((res)=>{
console.log(res)
})
}
}
然后我們在mounted這個生命周期中進行調(diào)用
mounted(){
this.getInfo()
}
這樣就可以在控制臺中查看數(shù)據(jù),以上是一個簡單的get方法數(shù)據(jù)請求,下面繼續(xù)介紹一下post方法的使用,其實post和get的使用沒有什么區(qū)別只是再加上一個參數(shù)就可以了,看一下我們的代碼
methods:{
postInfo(){
let url = "url"
let params=new URLSearchParams();//這個方法在axios的官網(wǎng)中有介紹,除了這個方法還有qs這個方法
params.append("key",index)
params.append("key",index)
axios.post(url,params).then((res)=>{
console.log(res)
})
}
}
同樣在mounted這個生命周期中進行調(diào)用
mounted(){
this.postInfo()
}
補充:下面看下axios 數(shù)據(jù)請求
項目地址:https://github.com/axios/axios
axios是一個基于Promise,同時支持瀏覽器端和Node.js的HTTP庫,常用于Ajax請求。
Vue.js 不像jQuery 或 AngularJS,本身并沒有帶Ajax方法,因此需要借助插件或第三方HTTP庫。
GET和POST請求
axios.get("./package.json",{
params:{
userId:"999"
},
headers:{
token:"jack"
}
}).then(res=>{
this.msg = res.data;
}).catch(function (error) {
console.log("error init."+error)
});
POST:
<code class="language-javascript"> axios.post("./package.json",{
userId:"888"
},{
headers:{
token:"tom"
}
}).then(res=>{
this.msg =res.data
}).catch(err=>{
console.log(err)
})</code>
基于Promise 可以執(zhí)行多個并發(fā)請求:1
function getUserAccount(){
return axios.get('/user/123')
}
function getUserPermissions(){
return axios.get('/user/12345/premissions')
}
axios.all([getUserAccount(),getUserPermissions()])
.then(axios.spread(function(acct,perms){
//請求都完時
}))
也可通過寫入配置的形式發(fā)起請求:
axios({
method:'post',
url:'/user/123',
data:{
firstName:'Fred',
lastName:'Flintstone'
}
}).then(function(res){
console.log(res)
})
在業(yè)務(wù)中經(jīng)常將其封裝為實例形式調(diào)用,便于通用配置:
// util.js
const instance = axios.create({
baseURL:"http://jsonplaceholder.typicode.com/",
timeout:1000,
headers:{"Content-Type":"application/x-www-form-urlencoded"}
})
export default instance;
在mounted中調(diào)用:
Ajax({
method:'post',
url:'/package.json',
data:{
firstName:'Fred',
lastName:'flintone'
}
}).then(res=>{
console.log(res.data)
this.msg = res.data
})
強求攔截可用于loading..
axios.interceptors.request.use(config=>{
console.log("require init");
return config
})
axios.interceptors.response.use(response=>{
console.log("response init");
return response
})
總結(jié)
以上所述是小編給大家介紹的vue axios數(shù)據(jù)請求get、post方法及實例詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
vue實現(xiàn)圖片拖拽及鼠標(biāo)滾輪放大縮小的示例代碼
本文主要給大家介紹如何vue實現(xiàn)圖片拖拽及鼠標(biāo)滾輪放大縮小,文中有詳細的代碼供大家參考,對我們的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2023-08-08
一文詳解Pinia和Vuex與兩個Vue狀態(tài)管理模式
這篇文章主要介紹了一文詳解Pinia和Vuex與兩個Vue狀態(tài)管理模式,Pinia和Vuex一樣都是是vue的全局狀態(tài)管理器。其實Pinia就是Vuex5,只不過為了尊重原作者的貢獻就沿用了這個看起來很甜的名字Pinia2022-08-08
vant 解決tab切換插件標(biāo)題樣式自定義的問題
這篇文章主要介紹了vant 解決tab切換插件標(biāo)題樣式自定義的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11

