Vue中封装axios的GET和POST请求

在vue项目中创建一个文件夹network

1.创建一个core.js文件,封装axios GET POST请求
代码如下:

import {GET,POST} from "./config"
import axios from "axios";



const instance = axios.create({
  baseURL:"https://api.it120.cc",//发送请求时,会在url前拼接baseUrl
  timeout:8000
})

	//封装GET POST
export function request(method,url,params){
  switch (method){
    case GET:
      return get(url,params)
    case POST:
      return post(url,params)
  }
}

function get(url,params){
  return instance.get(url,params)
}

function post(url,params){  
  return instance.post(url,params)
}

2.封装请求APl,处理接口数据

export const GET = "get";
export const POST ="post";

export const path ={
    list:"/small4/shop/goods/list",
  
}

3.抛出network模块

import {request} from "./core"
import {GET,path} from "./config"

const network = {
  getStoreList(params) {return request(GET,path.list,params)}, 
}
export default network;

4main.js中配置

import network from "./network/index";
Vue.prototype.$network = network;

5.在home中使用

<template>
  <div class="home">
    <button @click="onClick">点击</button>


    <div v-for="(item,index) in list" :key="index">
        {{item.name}}
      <img :src="item.pic" alt="" width="200px">

    </div>

  </div>
</template>

<script>
// @ is an alias to /src


export default {
  name: 'Home',
  data(){
      return{
        list:[],
      
      }
    },
  components: {
    
    
  },
  methods:{
    onClick(){
      this.$router.push(this.$routerConfig.about.path)
    }
  },
  //调用
  mounted(){
    this.$network.getStoreList({
      page:"1",
      pageSize:"10"
    }).then((response)=>{
      console.log(response.data.data)
      this.list=response.data.data
    }).catch((error)=>{
      console.log(error)
    })
   
  }
}
</script>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_48193717/article/details/107006031