我們常用的有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)用,便于通用配置:
新聞熱點
疑難解答
圖片精選