基于Vite+Vue3 给项目引入Axios

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

系列文章指路👉

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

安装依赖

npm install axios

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

const config = {
   baseUrl: '/boot-test'
}

export default config

进行简单封装

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

src目录下,新建utils,axios两个文件夹,新建index.js
在这里插入图片描述

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创建项目并配置常用的工具和一些常用的类
需要解决跨域问题,前后端解决都可以,我们本次采用前端解决。
2

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

调用尝试

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

<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>
  • 25
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小雅痞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值