国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

vue axios數(shù)據(jù)請求get、post方法及實例詳解

2024-05-06 15:30:16
字體:
供稿:網(wǎng)友

我們常用的有g(shù)et方法以及post方法,下面簡單的介紹一下這兩種請求方法

vue中使用axios方法我們先安裝axios這個方法

npm install --save axios

安裝之后采用按需引入的方法,哪個頁面需要請求數(shù)據(jù)就在哪個頁面里引入一下。

import axios from 'axios'

引入之后我們就可以進(jìn)行數(shù)據(jù)請求了,在methods中創(chuàng)建一個方法

 methods:{   getInfo(){     let url = "url"     axios.get(url).then((res)=>{       console.log(res)     })      }  }

然后我們在mounted這個生命周期中進(jìn)行調(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這個生命周期中進(jìn)行調(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)用,便于通用配置:

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 桃江县| 弥勒县| 东方市| 德惠市| 宜都市| 元氏县| 湖州市| 苏尼特右旗| 兴安县| 阿拉善盟| 乡宁县| 治县。| 尚志市| 平江县| 高州市| 施秉县| 四会市| 盐城市| 沛县| 张家界市| 家居| 岳西县| 太和县| 伊通| 秀山| 江华| 原阳县| 宝清县| 扎兰屯市| 闻喜县| 竹山县| 潞城市| 天门市| 常宁市| 诏安县| 甘德县| 公安县| 方城县| 高雄县| 延庆县| 三江|