axios安装与基本方法
生活随笔
收集整理的這篇文章主要介紹了
axios安装与基本方法
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
安裝:
1.npm安裝:
npm install axios2.在主入口文件main.js中引用:
import axios from 'axios'Vue.use(axios);3.在組件文件中的methods里使用:
<template><section class="jumbotron"><h3 class="jumbotron-heading">Search Github Users</h3><div><input type="text" placeholder="enter the name you search" v-model="keyWord"/> <button @click="searchUsers">Search</button></div></section> </template><script>import axios from 'axios'export default {name:'Search',data() {return {keyWord:''}},methods: {searchUsers(){//請求前更新List的數(shù)據(jù)this.$bus.$emit('updateListData',{isLoading:true,errMsg:'',users:[],isFirst:false})axios.get(`https://api.github.com/search/users?q=${this.keyWord}`).then(response => {console.log('請求成功了')//請求成功后更新List的數(shù)據(jù)this.$bus.$emit('updateListData',{isLoading:false,errMsg:'',users:response.data.items})},error => {//請求后更新List的數(shù)據(jù)this.$bus.$emit('updateListData',{isLoading:false,errMsg:error.message,users:[]})})}},} </script>常用API:
1.get請求:查詢數(shù)據(jù),直接從后臺獲取數(shù)據(jù),參數(shù)寫在地址(url)里,第一個參數(shù)是url(API的一個地址,由后端提供);
2.post請求:添加數(shù)據(jù),一般在填寫表單并提交時,要將輸入的數(shù)據(jù)寫在數(shù)據(jù)庫里,參數(shù)一般放在對象中;
3.put請求:修改數(shù)據(jù)
4.delete請求:刪除數(shù)據(jù)
使用方式示例
1.執(zhí)行g(shù)et數(shù)據(jù)請求
axios.get('url',{params:{id:'接口配置參數(shù)(相當(dāng)于url?id=xxxx)',}, }) .then((res)=>{console.log(res); // 處理成功的函數(shù) 相當(dāng)于success }) .catch((error)=>{console.log(error) // 錯誤處理 相當(dāng)于error })2.執(zhí)行post數(shù)據(jù)發(fā)送
const data = {name:'張三',age:23 } axios.post('url',data) .then((res)=>{console.log(res); // 處理成功的函數(shù) 相當(dāng)于success }) .catch((error)=>{console.log(error) // 錯誤處理 相當(dāng)于error })3.執(zhí)行delete 數(shù)據(jù)發(fā)送
// 如果服務(wù)端將參數(shù)作為java對象來封裝接受 axios.delete('demo/url', {data: {id: 123,name: 'Henry',},timeout: 1000, }) // 如果服務(wù)端將參數(shù)作為url參數(shù)來接受,則請求的url為:www.demo/url?a=1&b=2形式 axios.delete('demo/url', {params: {id: 123,name: 'Henry',},timeout: 1000 })4.執(zhí)行put 數(shù)據(jù)發(fā)送
axios.put('demo/url', {id: 123,name: 'Henry',sex: 1,phone: 13333333 })示例摘自:
?axios使用方法 - 簡書
總結(jié)
以上是生活随笔為你收集整理的axios安装与基本方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。