vue3+ts 代理的使用

简单封装request.ts

import  axios  from  "axios";

// 1.创建axios对象
const  service=axios.create();

// 2.请求拦截器
service.interceptors.request.use(config=>{
    return  config;
},error=>{
    Promise.reject(error);
})

// 3.响应拦截器
service.interceptors.response.use(response=>{
    // 判断code码
    return  response.data;

},error=>{
    return  Promise.reject(error)
})

export default service;

api请求实例:

import  request  from "@/utils/request";

export const getSliders=()=>{
    return  request({
        url:"/api/slider/getSliders"
    })
}

设置代理 vite-config.ts

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from "path"
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    // 配置路径别名
    alias: {
      "@":path.resolve(__dirname,'./src')
    }
  },
  server:{
    proxy:{
      "/api":"http://127.0.0.1:9999/"
    }
  }
})

在页面中使用:

<template>
  <div>
    <el-carousel indicator-position="outside" height="400px">
      <el-carousel-item v-for="item in imgUrls" :key="item">
        <img :src="item.imageUrl" alt="轮播图" class="img" />
      </el-carousel-item>
    </el-carousel>
  </div>
</template>

<script setup lang="ts">
import { onBeforeMount, ref } from "vue";
import { getSliders } from "@/api/slider";

let imgUrls = ref([]);
onBeforeMount(() => {
  getSliders().then((res: any) => {
    console.log(res, "请求结果");
    imgUrls.value = res.data;
  });
});
</script>

<style>
.img {
  width: 100%;
}
</style>

效果图:

vue3+ts 代理的使用_第1张图片

你可能感兴趣的:(vue.js,javascript,前端)