vue使用axios后端发送数据

下载axios npm install axios
axios前端像后台发送数据
然后再src/main.js文件夹里配置信息
// The Vue build version to load with the import command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from ‘vue’
import App from ‘./App’
import router from ‘./router’
import axios from ‘axios’
Vue.config.productionTip = false
// 全局使用
Vue.prototype.axios = axios
/* eslint-disable no-new */
new Vue({
el: ‘#app’,
router,
components: { App },
template: ‘’
})

### Vue 使用 Axios 进行前后端数据交互 #### 方法一:定义全局方法并调用 为了简化开发流程,可以在项目的`utils/request.js`文件中创建一个通用的HTTP请求工具类[^2]。 ```javascript // utils/request.js import axios from 'axios' export function getList() { return axios.get('http://localhost:8080/api/data'); } ``` 在组件内部可以通过引入此函数来发起网络请求: ```javascript <script> import {getList} from '@/utils/request'; export default { data() { return { dataList: [] } }, methods: { fetchData() { getList().then(response => { this.dataList = response.data; }).catch(error => { console.error("There was an error fetching the data!", error); }); } }, mounted() { this.fetchData(); } }; </script> ``` #### 方法二:直接在组件内集成Axios实例 如果不想额外配置公共API接口,则可以直接在单个Vue组件里边导入和使用axios库[^3]。 ```html <template> <div class="example"> <!-- 组件模板 --> </div> </template> <script> import axios from "axios"; export default { name: "ExampleComponent", data() { return { responseData: null, }; }, created() { this.test(); }, methods: { test() { this.axios.get("/api/user/test").then((res) => { console.log(res.data); // 处理返回的数据 }); }, }, }; </script> ``` 上述两种方式都可以实现前端向后端发送GET请求的功能。第一种更适合大型应用,有助于维护统一的API管理;第二种则更加灵活便捷适用于小型项目或快速原型设计。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值