一、Vue中Get請求傳參
在Vue中進行Get請求時,傳遞參數是一個必不可少的過程。我們可以通過url後面加上請求參數來傳遞基本類型(如字元串、數字等)參數。例如:
axios.get('/api/getData?id=1&name=Tom')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
如果要傳遞多個參數,可以使用”&”將多個參數拼接起來。
二、Vue中Get請求的寫法
在Vue中可以使用axios來發送Get請求,它是一個基於Promise的HTTP庫,可以用在瀏覽器和Node.js中。
使用axios發送Get請求的寫法如下:
axios.get('/api/getData')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
這裡的’/api/getData’表示訪問的地址,後端接收這個請求後返迴響應數據。
三、Vue中Get請求傳遞參數
如果要在Vue中以參數形式傳遞對象或者數組,需要在請求時使用params參數傳遞。例如:
// 傳遞對象
axios.get('/api/getData', {
params: {
id: 1,
name: 'Tom'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 傳遞數組
axios.get('/api/getData', {
params: {
ids: [1, 2, 3]
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
四、Vue中Get請求url跟一個對象
如果我們想要在Vue中Get請求時,將參數放到請求url後面,且只有一個對象作為參數傳遞。這時我們可以使用qs庫,qs庫是一個處理URL查詢字元串的js庫。
// 首先安裝qs庫
npm install qs
// 然後在代碼中引入qs庫
import qs from 'qs'
// Get請求url跟一個對象
axios.get('/api/getData?' + qs.stringify({
id: 1,
name: 'Tom'
}))
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
五、Vue中Get請求傳多個不同類型參數
如果我們需要在Vue中Get請求時,傳遞多個不同類型的參數,包括字元串、布爾值、數字等,我們可以使用params參數傳遞。
axios.get('/api/getData', {
params: {
id: 1,
name: 'Tom',
isVip: true,
age: 30
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
六、Vue中Put請求
在Vue中進行Put請求,可以使用axios庫,與Get請求的使用基本相同,只需將get改為put,其他參數不變。例如:
axios.put('/api/updateData', {
id: 1,
name: 'Tom'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
七、Vue請求數據
在Vue中請求數據有多種方式,其中Get請求是最基本的一種方式,可以應用於大多數場景。除此之外還有Post、Put、Delete等請求方式可以使用,具體使用方法請參考axios文檔。
八、Vue請求後端數據
在Vue中請求後端數據的過程其實很簡單,只需要將後端的介面地址作為請求地址即可。例如:
// 後端介面地址為'/api/getData'
axios.get('/api/getData')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
注意:請確保後端已經開啟了相關的介面服務,否則會無法請求到數據。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/152585.html