vueにAxiosをカプセル化する


vueパッケージaxiosとコンポーネントはsrcディレクトリの下で新しいstoreフォルダを多重化して新しいfetchを作成する.jsファイル導入axios
import axios from ‘axios’ //
export function fetch(options){ // fetch
return new Promise((resolve,reject)=>{ //
const instance =axios,create({ // axios
headers:{ //
‘Content-Type’ : ‘application/json’, //
‘token’ : localStorage.getItem(‘obj’) // token , vuex
},
timeout: 5*1000 //
})
instance(options).then(response=>{ // response
resolve(response)
})
.catch(error=>{ //
console.log(‘ ’+error)
reject(error)
})
})
}
storeフォルダの下に新しいjsファイルを作成するfetchファイルインスタンス化要求、例えばapiを導入する.jsの
import {fetch} form ‘./fetch’ // fetch.js fetch
import global_ from ‘…/Global’ // Global.vue const BASE_URL
export function GetAllUser (page,name,email,roleName){ // , , , , ,
return fetch ({ // fetch , headers
url: global_.BASE_URL+’/user/getAlluser’, // url ,
method:‘post’, // post, data, get prams
data: JSON.stringify({ // JSON
page: page,
name:name,
email:email,
roleName:roleName
})
})
}
複数のリクエストを上のようにもう1つ書けばいいので、複数のjsファイルを新規作成して異なるインタフェースタイプを分離してvueコンポーネントでパラメータを渡し、成功した後のレンダリングを実行できます.
// html  

//  js       click         
import {GetAllUser} from '../../store/api'            //               form      

//  methods   

search(){    //       
GetAllUser(this.currentPage,this.name,this.email,this.region)   //     
.then((res)=>{  
this.total=res.data.num           //                 total,        
this.tabledata=res.data.data      //      data             ,      
})
.catch((error)=>{                //     
console.log('    :'error)          //       
})
}

一般的なプロジェクトには多くのリクエストが書かれており、ページとは異なるリクエストをカプセル化してjsファイルに置くことができます.