Vue-axios
axios请求
一个基于 Promise 的 HTTP 客户端,用于浏览器和 node.js
主要的作用是:
- 发送 HTTP 请求:可以发送 GET、POST、PUT、DELETE 等各种类型的 HTTP 请求。
- 拦截请求和响应:可以在请求或响应被处理之前拦截它们,进行一些操作,如设置请求头、转换请求数据、处理错误等。
- 取消请求:允许取消已经发出的请求。
- 自动转换 JSON 数据:发送请求时会自动将 JavaScript 对象序列化为 JSON 字符串,接收响应时会将 JSON 字符串自动解析为 JavaScript 对象。
// 本地安装 npm install axios import axios from 'axios';
<!-- 通过CDN的方式引用axios --> <script src="https://unpkg.com/axios@1.4.0/dist/axios.min.js"></script>
常用的HTTP请求方式:
- GET: 获取数据
- POST: 新增数据
- PUT: 修改数据
- DELETE: 删除数据
axios的请求方法
- axios.get: 发送GET请求
- axios.post: 发送POST请求
- axios.put: 发送PUT请求
- axios.delete: 发送DELETE请求
使用json-server模拟接口服务
Json-Server 是一个零配置的 REST API 服务器,它主要的作用是:
- 提供模拟的后端服务:通过创建一个 JSON 文件来模拟数据库,Json-Server 可以快速生成一个完整的 RESTful API。
- 支持增删改查操作:允许通过标准的 HTTP 方法(GET、POST、PUT、DELETE)对数据进行操作。
- 自定义路由和中间件:可以通过自定义路由和中间件来扩展 API 功能。
安装json-server
npm i json-server -D
准备数据文件mock/data.json
{ "users": [ {"id": 1, "name": "xiaoming"}, {"id": 2, "name": "xiaomei"}, {"id": 3, "name": "xiaopang"} ] }
编写启动脚本package.json
{ "name": "vite-vue", "version": "0.0.0", "private": true, "type": "module", "scripts": { "dev": "vite", "build": "vite build", "preview": "vite preview", // 添加server脚本 // --watch 参数会让 json-server 监听数据文件的变化并自动重启 // --port 3000 参数指定了服务器运行的端口 "server": "json-server mock/data.json" }, "dependencies": { "axios": "^1.7.7", "vue": "^3.5.12" }, "devDependencies": { "@vitejs/plugin-vue": "^5.1.4", "json-server": "^1.0.0-beta.3", "vite": "^5.4.10", "vite-plugin-vue-devtools": "^7.5.4" } }
启动json-server服务
npm run server
基本使用
通过axios
对象调用其方法, 发送对应的HTTP请求
<!-- 通过CDN的方式引用axios --> <script src="https://unpkg.com/axios@1.4.0/dist/axios.min.js"></script> <script> // 通过axios对象, 调用get方法, 发送GET请求 // get 返回promise对象 axios.get('http://localhost:3000/users').then((res) => { // json-server 返回的数据 保存在res中, 使用data console.log(res) }) </script> </body> </html>
增删改查
<body> <button onclick="addUser()">添加</button> <button onclick="updateUser(1)">修改</button> <button onclick="removeUser(1)">删除</button> <script> axios.get('http://localhost:3000/users').then(res => { console.log(res) }) function addUser() { // 通过axios对象, 调用post方法, 发送post请求 axios .post('http://localhost:3000/users', { name: 'test', }) .then(res => {console.log(res)}) } function updateUser(id) { // 通过axios对象, 调用put方法, 发送put请求 axios .put(`http://localhost:3000/users/${id}`, { name: 'test-new', }) .then((res) => { console.log(res) }) } function removeUser(id) { // 通过axios对象, 调用delete方法, 发送delete请求 axios.delete(`http://localhost:3000/users/${id}`).then((res) => { console.log(res) }) } </script> </body> </html>
集成到Vue
- 启动服务
在目录下创建数据文件mock/data.json
运行脚本: npm run server
-
axios的二次封装
- 定义baseURL
- 定义超时时间
- 定义响应拦截器
创建api/request.js
文件
// 1. 导入axios import axios from 'axios' // 2. 创建实例 const instance = axios.create({ baseURL: 'http://localhost:3000', timeout: 3000, }) // 3. 定义拦截器 instance.interceptors.response.use( (res) => { return res.data }, (error) => { return Promise.reject(error) } ) // 4. 导出实例 export default instance
创建接口文件api/users.js
import request from './request' // 获取所有用户: GET /users export function getUsers() { return request({ url: '/users', method: 'GET', }) } // 获取单个用户: GET /users/:id export function getUserById(id) { return request({ url: `/users/${id}`, method: 'GET', }) } // 添加用户: POST /users {name: 'xiaoming'} export function addUser(name) { return request({ url: '/users', method: 'POST', data: { name, }, }) } // 修改用户: PUT /users/1 {name: 'xiaoming-new'} export function updateUser(id, name) { return request({ url: `/users/${id}`, method: 'PUT', data: { name, }, }) } // 删除用户: DELETE /users/1 export function removeUser(id) { return request({ url: `/users/${id}`, method: 'DELETE', }) }
- 编写页面
实现静态页面
<template> <div>添加用户: <input type="text" /> <button>添加</button></div> <ul> <li> <span>xiaoming</span> <button>修改</button> <button>删除</button> </li> <li> <span>xiaoming</span> <button>修改</button> <button>删除</button> </li> </ul> </template> <script setup></script> <style scoped></style>
实现列表功能
<template> <div>添加用户: <input type="text" /> <button>添加</button></div> <ul> <li v-for="user in users" :key="user.id"> <span>{{ user.name }}</span> <button>修改</button> <button>删除</button> </li> </ul> </template> <script setup> import { onMounted, ref } from 'vue' // 导入接口 import { getUsers } from '../api/users.js' // 定义数据 const users = ref([]) // 初始化数据 onMounted(async () => { users.value = await getUsers() }) </script> <style scoped></style>
实现添加功能
<template> <div> 添加用户: <input type="text" v-model="name" /> <button @click="add">添加</button> </div> <ul> <li v-for="user in users" :key="user.id"> <span>{{ user.name }}</span> <button>修改</button> <button>删除</button> </li> </ul> </template> <script setup> import { onMounted, ref } from 'vue' // 导入接口 import { getUsers as getUsersAPI, addUser } from '../api/users.js' // 定义数据 const users = ref([]) const name = ref('') // 初始化数据 onMounted(getUsers) // 定义方法 async function getUsers() { users.value = await getUsersAPI() } async function add() { const res = await addUser(name.value) alert('添加成功') getUsers() name.value = '' } </script> <style scoped></style>
实现修改删除
<template> <div> 添加用户: <input type="text" v-model="name" /> <button @click="add">添加</button> </div> <ul> <li v-for="user in users" :key="user.id"> <span>{{ user.name }}</span> <button @click="update(user.id)">修改</button> <button @click="remove(user.id)">删除</button> </li> </ul> </template> <script setup> import { onMounted, ref } from 'vue' // 导入接口 import { getUsers as getUsersAPI, addUser, updateUser, removeUser, } from '../api/users.js' // 定义数据 const users = ref([]) const name = ref('') // 初始化数据 onMounted(getUsers) // 定义方法 async function getUsers() { users.value = await getUsersAPI() } async function add() { const res = await addUser(name.value) alert('添加成功') getUsers() name.value = '' } async function update(id) { const name = prompt('请输入新的用户名') const res = await updateUser(id, name) alert('修改成功') getUsers() } async function remove(id) { const res = await removeUser(id) alert('删除成功') getUsers() } </script> <style scoped></style>
本文作者:Khru
本文链接:https://www.cnblogs.com/khrushchefox/p/18573290
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步