alova 是一个轻量级的请求策略库,简单来说就是可以通过它发送HTTP请求给服务器。
npm install alova --save
import { createAlova } from 'alova';
// v2.0
// import GlobalFetch from 'alova/GlobalFetch';
// v3.0
import adapterFetch from 'alova/fetch';
import VueHook from 'alova/vue'
export const alovaInstance = createAlova({
// 假设我们需要与这个域名的服务器交互
baseURL: 'http://jsonplaceholder.typicode.com',
// 将 alova 库与 Vue.js 框架集成,使得 alova 可以管理 Vue 组件的状态
statesHook: VueHook,
// 请求适配器,这里我们使用fetch请求适配器
requestAdapter: adapterFetch(),
// 设置全局的请求拦截器,与axios相似
beforeRequest() {},
// 响应拦截器,也与axios类似
responded: {
onSuccess: async (response) => {
const json = await response.json()
// 根据后端约定,判断code值抛出对应的问题
if (json.code === 1) {
return json.data
} else {
console.log(json.msg)
throw new Error(json.msg)
}
},
// 抛出错误时,将会进入请求失败拦截器内
onError(error) {
throw new Error(error)
}
}
});
<template>
<div>
<button @click="handleGet">get</button>
<button @click="handlePost">post</button>
<button @click="handlePut">put</button>
<button @click="handleDelete">delete</button>
</div>
</template>
<script lang="ts" setup>
import { alovaInstance } from '../alova/index';
// 定义异步函数handleGet
async function handleGet() {
const response = await alovaInstance.Get('/posts');
}
// 定义异步函数handlePost
async function handlePost() {
const response = await alovaInstance.Post('/posts',{
title: 'foo',
body: 'bar',
userId: 1,
});
}
// 定义异步函数handlePut
async function handlePut() {
const response = await alovaInstance.Put('/posts/1',{
id: 1,
title: 'foo1',
body: 'bar1',
userId: 1,
});
}
// 定义异步函数handleDelete
async function handleDelete() {
const response = await alovaInstance.Delete('/posts/1');
}
</script>