https://www.cnblogs.com/wuhuacong/p/12986166.html
1.axios?axios 是一個(gè)基于Promise 用于瀏覽器和 nodejs 的 HTTP 客戶端铺峭,本質(zhì)上也是對(duì)原生XHR的封裝,只不過它是Promise的實(shí)現(xiàn)版本鸥印,符合最新的ES規(guī)范找蜜。在這里我們只需要知道它是非常強(qiáng)大的網(wǎng)絡(luò)請(qǐng)求處理庫,且得到廣泛應(yīng)用即可
(1)post方法
axios({
? ? method: 'post',
? ? url: '/user/12345',
? ? data: {
? ? ? ? firstName: 'Fred',
? ? ? ? lastName: 'Flintstone'
? ? }
})
.then(function (response) {
? ? console.log(response);
})
.catch(function (error) {
? ? console.log(error);
});
(2)get請(qǐng)求
axios
? .get('http://rap2api.taobao.org/app/mock/23080/resources/search',{
? ? ? params: {
? ? ? ? id: 5
? ? ? }
? })
? .then(res => {
? ? console.log('數(shù)據(jù)是:', res);
? })
? .catch((e) => {
? ? console.log('獲取數(shù)據(jù)失敗');
? });
2.(1)一般前端調(diào)用婚被,通過前端API類的封裝狡忙,即可發(fā)起對(duì)后端API接口的調(diào)用,request是對(duì)Axios的簡(jiǎn)單封裝址芯,主要就是攔截注入一些登錄信息和一些響應(yīng)的錯(cuò)誤處理而已灾茁。返回是一個(gè)JSON數(shù)據(jù)集合
import request from '@/utils/request'
export? function GetProductList (id) { //方法名? ? ?(params)
? return request({
? ? url: '/abp/services/app/User/Get',? ?//與后端協(xié)調(diào)好的接口
? ? method: 'get',
? ? params: {id}? ?//params
? })
}
(2)JS處理部分,可以直接引入API進(jìn)行請(qǐng)求數(shù)據(jù)
import{ GetProductList }from'@/api/product'? //project是api文件夾中的product.js文件谷炸,vue中通常寫下
(3)然后我們就可以在method方法里面定義一個(gè)獲取API數(shù)據(jù)的方法了北专。
methods: {
? ? getlist(type) {
? ? ? GetProductList({ type: type }).then(response => {
? ? ? ? const { data } = response
? ? ? ? this.productlist = data.list
? ? ? ? this.listLoading =false? ? ? })
? ? }
這種調(diào)用是最直接的API調(diào)用,沒有引入Store模塊中封裝的Action或者M(jìn)utation進(jìn)行異步或者同步的處理旬陡。一般情況下直接使用這種方式比較簡(jiǎn)潔拓颓,因?yàn)榇蠖鄶?shù)頁面處理或者組件處理,不需要對(duì)數(shù)據(jù)進(jìn)行全局狀態(tài)的存儲(chǔ)處理描孟,也就是不需要進(jìn)行全局Store對(duì)象的處理了驶睦。
如果我們需要在全局存儲(chǔ)對(duì)應(yīng)的信息,那么就需要引入Store模塊中對(duì)API調(diào)用的封裝了匿醒,包括Action或者M(jìn)utation的處理场航。如果我們需要對(duì)產(chǎn)品列表等數(shù)據(jù)進(jìn)行全局狀態(tài)的存儲(chǔ),那么我們可以考慮創(chuàng)建一個(gè)對(duì)應(yīng)Store目錄下的模塊廉羔,如product.js溉痢,來管理Action、Mutation和State等信息。如果引入了Store模塊的業(yè)務(wù)類孩饼,那么在界面視圖中調(diào)用代碼則修改為調(diào)用對(duì)應(yīng)的Action或者M(jìn)utation了髓削。
methods: {
? ? getlist(type) {
? ? ? // GetProductList({ type: type }).then(response => {
? ? ? //? const { data } = response
? ? ? //? this.productlist = data.list
? ? ? //? this.listLoading = false?
? ? ? // })
? this.$store.dispatch('product/getProductList', { type: type }).then(data => {
? ? ? ? this.productlist = data.list
? ? ? ? // this.loading = false
? ? ? ? }).catch((e) => {
? ? ? ? // this.loading = false? ? ??
? ? ? ? })
? ? }
一般情況下在視圖模塊中使用API的類調(diào)用即可,不需要累贅的每個(gè)業(yè)務(wù)模塊镀娶,都創(chuàng)建一個(gè)Store的模塊類進(jìn)行相應(yīng)的管理立膛,只有在這些狀態(tài)數(shù)據(jù)需要在多個(gè)頁面或者組件中需要共享的時(shí)候,才考慮引入Store模塊類進(jìn)行細(xì)化管理汽畴。如果需要?jiǎng)?chuàng)建對(duì)應(yīng)業(yè)務(wù)模塊的Store狀態(tài)管理模塊旧巾,那么需要?jiǎng)?chuàng)建對(duì)應(yīng)的模塊類,如前面說到的product.js類文件忍些。