常寧網(wǎng)頁設(shè)計(jì)西安百度關(guān)鍵詞優(yōu)化排名
基于Vite+Vue3 給項(xiàng)目引入Axios,方便與后端進(jìn)行通信。
系列文章指路👉
系列文章-基于Vue3創(chuàng)建前端項(xiàng)目并引入、配置常用的庫和工具類
文章目錄
- 安裝依賴
- 新建src/config/config.js 用于存放常用配置
- 進(jìn)行簡(jiǎn)單封裝
- 解決跨域問題
- 調(diào)用嘗試
安裝依賴
npm install axios
新建src/config/config.js 用于存放常用配置
const config = {baseUrl: '/boot-test'
}export default config
進(jìn)行簡(jiǎn)單封裝
引用階段先簡(jiǎn)單封裝,后續(xù)有復(fù)雜功能添加進(jìn)來再進(jìn)行改造。
src目錄下,新建utils,axios兩個(gè)文件夾,新建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
解決跨域問題
復(fù)用我們之前的后端項(xiàng)目,作為Vue3的后端:系列文章-基于SpringBoot3創(chuàng)建項(xiàng)目并配置常用的工具和一些常用的類
需要解決跨域問題,前后端解決都可以,我們本次采用前端解決。
server: {open: true,// 啟動(dòng)項(xiàng)目自動(dòng)彈出瀏覽器port: 4000,// 啟動(dòng)端口proxy: {'/boot-test': {target: 'http://localhost:8001/boot-test', // 實(shí)際請(qǐng)求地址changeOrigin: true,rewrite: (path) => path.replace(/^\/boot-test/, '')},}},
調(diào)用嘗試
寫個(gè)小demo,把后端請(qǐng)求到的水果列表展示到前端表格上。
<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: '價(jià)格',dataIndex: 'frPrice',key: 'frPrice',minWidth: 120},)return columns
}
</script><style scoped></style>