Vue-axios的基本使用(一)

Vue-axios的基本使用 一

axios请求方式

支持多种请求方式:

  • axios(config)
  • axios.request(config)
  • axios.get(url[,config])
  • axios.delete(url[,config])
  • axios.head(url[,config])
  • axios.post(url[,data[,config]])
  • axios.put(url[,data[,config]])
  • axios.patch(url[,data[,config]])

重点讲解axios(config)

//1.
axios({
	//httpbin.org网站可以模拟传参
	url:'httpbin.org',
	//method:'可以指定请求类型(默认为get)'
	method:'get'
	//then是用来拿到res(结果)
}).then(res =>{ 
	//打印结果
	console.log(res);
})
//2.如果url中有参数
axios({
	url:'http://123.111.32.32:8000/home/data?type=sell&page=3'
}).then(res => {
	console.log(res);
})
//还有一种方法
axios({
	url:'http://123.111.32.32:8000/home/data',
	params: {
	type:'pop'
	page:'1'
}
}).then(res => {
	console.log(res);
})
//3.
axios.get(url,对应的其他配置).then({

})
Vue3结合`vue-axios`可以很方便地进行HTTP请求操作,下面是个简单的介绍和步骤。 ### 安装 首先需要安装`axios`以及其Vue插件`vue-axios`。你可以通过npm或yarn完成这个任务: ```bash # 使用 npm 的命令行工具来安装 axiosvue-axios 插件 npm install axios vue-axios # 或者如果你更喜欢 yarn 包管理器的话,则运行此命令 yarn add axios vue-axios ``` ### 引入并注册插件 在项目的入口文件(main.js)里引入并使用它: ```javascript import { createApp } from 'vue'; import App from './App.vue'; // 导入 axios 库以及 vue-axios 插件 import axios from "axios"; import VueAxios from "vue-axios"; const app = createApp(App); app.use(VueAxios, axios); app.mount('#app'); ``` ### 发起请求 之后就可以直接在组件内部利用 this.$http 来发起请求了,比如获取数据、提交表单等场景下都会用到。 #### 示例代码 - 获取用户列表 (GET) 假设我们有个API端点 `/api/users`, 需要从中检索所有用户的记录作为例子演示 GET 请求的过程. ```html <template> <div id="example"> <!-- 用户信息将显示在这里 --> Users List:<br/> <ul v-if="users && users.length" style="list-style:none;"> <li v-for="(user,index) in users" :key="index">{{ user.name }}</li> </ul> <!-- 错误消息将会显示在此处 --> <p v-if="errors">{{ errors }}</p> </div> </template> <script> export default { data() { return { errors: [], users: [] // 这里用于存储从服务器接收到的数据 }; }, created() { // 组件创建完成后立即发送异步 HTTP 请求. this.fetchUsers(); }, methods: { fetchUsers () { this.axios.get(`/api/users`) .then(response => { // 成功接收响应后的处理逻辑... console.log('Response:', response.data) this.users = response.data; }) .catch(error => { // 如果发生错误则捕获异常,并将其赋值给 `this.errors` console.error("There was an error fetching the users!",error); this.errors.push(error.response.data || error.message); }); } } } </script> ``` 以上就是关于如何在Vue3项目里面集成与使用`vue-axios`的基本指南啦!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值