我們常用的有get方法以及post方法,下面簡單的介紹一下這兩種請求方法
vue中使用axios方法我們先安裝axios這個方法
npm install --save axios
安裝之后采用按需引入的方法,哪個頁面需要請求數據就在哪個頁面里引入一下。
import axios from 'axios'
引入之后我們就可以進行數據請求了,在methods中創建一個方法
1 methods:{
2 getInfo(){ 3 let url = "url" 4 axios.get(url).then((res)=>{ 5 console.log(res) 6 }) 7 } 8 }
然后我們在mounted這個生命周期中進行調用
1 mounted(){
2 this.getInfo() 3 }
這樣就可以在控制台中查看數據,以上是一個簡單的get方法數據請求,下面繼續介紹一下post方法的使用,其實post和get的使用沒有什么區別只是再加上一個參數就可以了,看一下我們的代碼
1 methods:{
2 postInfo(){ 3 let url = "url" 4 let params=new URLSearchParams();//這個方法在axios的官網中有介紹,除了這個方法還有qs這個方法 5 params.append("key",index) 6 params.append("key",index) 7 axios.post(url,params).then((res)=>{ 8 console.log(res) 9 }) 10 } 11 }
同樣在mounted這個生命周期中進行調用
1 mounted(){
2 this.postInfo() 3 }
