1. 程式人生 > 實用技巧 >vue-axios 封裝

vue-axios 封裝

自定義一個request.js檔案用來封裝axios

import axios from 'axios' //匯入axios

const instance=axios.create({
  baseURL:"https:api.cat-shop.penkuoer.com",//baseURL會在傳送請求的時候拼接在url引數前面,在不同的生產環境中修改這個就行了
  timeout:5000
})

export function get(url,params){//封裝get傳入URL和params
  return instance.get(url,{
    params
  });
}

export function post(url,data){
//封裝post傳入URL和data return instance.post(url,data); } export function del(url){//封裝del傳入URL return instance.delete(url); } export function put(url,data){//封裝put傳入URL和data return instance.put(url,data); }

使用

<template>
  <div>
    <button @click="getByMineRequest()">呼叫封裝的get獲取後端資料</button>
  </div>
</template>

<script>
  import {
get} from '../../utils/request.js'//匯入request檔案 export default { name: "HelloWorld", methods: { getByMineRequest:function(){ get("/api/v1/products",{})//呼叫reques中的get方法傳入路徑(路徑會自動拼接在instance後面)和空的params
        .then(function(response){
          console.log(response)
        })
      }
    }
  }
</script> <style> </style>