基于Vite+Vue3 给项目引入Axios

基于Vite+Vue3 给项目引入Axios,方便与后端进行通信。

系列文章指路👉

系列文章-基于Vue3创建前端项目并引入、配置常用的库和工具类

文章目录

安装依赖

npm install axios

新建src/config/config.js 用于存放常用配置

javascript 复制代码
const config = {
   baseUrl: '/boot-test'
}

export default config

进行简单封装

引用阶段先简单封装,后续有复杂功能添加进来再进行改造。

src目录下,新建utils,axios两个文件夹,新建index.js

javascript 复制代码
import axios from 'axios'
import config from "@/config/config.js";

const http = axios.create()
http.defaults.baseURL = config.baseUrl
http.defaults.timeout = 15 * 1000
http.defaults.headers.common['Content-Type'] = 'application/json;charset=UTF-8'

export default http

解决跨域问题

复用我们之前的后端项目,作为Vue3的后端:系列文章-基于SpringBoot3创建项目并配置常用的工具和一些常用的类

需要解决跨域问题,前后端解决都可以,我们本次采用前端解决。

javascript 复制代码
    server: {
        open: true,// 启动项目自动弹出浏览器
        port: 4000,// 启动端口
        proxy: {
            '/boot-test': {
                target: 'http://localhost:8001/boot-test',	// 实际请求地址
                changeOrigin: true,
                rewrite: (path) => path.replace(/^\/boot-test/, '')
            },
        }
    },

调用尝试

写个小demo,把后端请求到的水果列表展示到前端表格上。

html 复制代码
<template>
  <h3>
    展示水果列表
  </h3>
  <div style="width: 1000px;">
    <a-table bordered  :scroll="{ y: 300 }"
             :dataSource="tableData" :columns="tableColumn"/>
  </div>

</template>

<script setup>
import {ref} from 'vue';
import http from "@/utils/axios/index.js";

let tableData = ref([])
let tableColumn = initColumns()
getAjaxData()

function getAjaxData() {
  http.get("/goods/fruit/list")
      .then(resp => {
        if (resp && resp.data.code === 200) {
          tableData.value = resp.data.data
        }
      })
      .catch(err => {
      })
}
function initColumns(){
  let columns = []
  columns.push(
      {
        title: '编码',
        dataIndex: 'frCode',
        key: 'frCode',
        minWidth: 150
      },
      {
        title: '名称',
        dataIndex: 'frName',
        key: 'frName',
        minWidth: 200
      },
      {
        title: '价格',
        dataIndex: 'frPrice',
        key: 'frPrice',
        minWidth: 120
      },
  )
  return columns
}
</script>

<style scoped>

</style>
相关推荐
YUELEI11811 小时前
构建electron项目
electron·vue3
陈逸子风13 小时前
(系列五).net8 中使用Dapper搭建底层仓储连接数据库(附源码)
vue3·webapi·权限·流程
古韵2 天前
用alovajs的use-fetcher,轻松搞定数据请求难题
前端·javascript·axios
Small-K2 天前
前端框架中@路径别名原理和配置
前端·webpack·typescript·前端框架·vite
学习使我快乐012 天前
AJAX 1——axios体验、认识URL、常用请求方法、HTTP协议、错误处理、form-serialize插件
前端·http·ajax·okhttp·axios
小茹想睡觉5 天前
vite 底层解析
vite
闪光桐人6 天前
uniapp/vue项目 import 导入文件时提示Module is not installed,‘@/views/xxx‘路径无法追踪
前端·vue.js·webpack·uni-app·vite
一雨方知深秋7 天前
Element-plus安装及其基础组件使用
javascript·css·html·vue3·element-plus
清晨-阳光zx7 天前
vue-i18n在使用$t时提示类型错误
vue3·vue-i18n
陈逸子风8 天前
从0到1搭建权限管理系统系列四 .net8 中Autofac的使用(附源码)
vue3·webapi·权限·流程·表单