监听请求
在一些需要随数据变化而重新请求的场景下,如分页、数据筛选、模糊搜索,可以使用useWatcher 来监听指定的状态变化时立即发送请求。
提醒
在使用 useWatcher 前,请确保已设置 statesHook。
关键字搜索
接下来我们以搜索 todo 项为例,尝试改变选择框中的选项,看看 todo 列表是如何变化的。
- vue
- react
- svelte
- vue options
<script>
import { writable } from 'svelte/store';
// 创建method实例
const filterTodoList = userId => {
return alovaInstance.Get(`/users/${userId}/todos`);
};
const userId = writable(0);
const { loading, data, error } = useWatcher(
// 参数必须设置为返回method实例的函数
() => filterTodoList($userId),
// 被监听的状态数组,这些状态变化将会触发一次请求
[userId]
);
</script>
<select bind:value="{$userId}">
<option value="{1}">User 1</option>
<option value="{2}">User 2</option>
<option value="{3}">User 3</option>
</select>
<!-- 渲染筛选后的todo列表 -->
{#if $loading}
<div>Loading...</div>
{:else}
<ul>
{#each $data as todo}
<li class="todo-title">{{ todo.completed ? '(Completed)' : '' }}{{ todo.title }}</li>
{/each}
</ul>
{/if}
分页
以 todo 列表分页请求为例,你可以这样做。
- vue
- react
- svelte
- vue options
<template>
<!-- ... -->
</template>
<script setup>
// method实例创建函数
const getTodoList = currentPage => {
return alovaInstance.Get('/todo/list', {
params: {
currentPage,
pageSize: 10
}
});
};
const currentPage = ref(1);
const { loading, data, error } = useWatcher(
// 第一个参数为返回method实例的函数,而非method实例本身
() => getTodoList(currentPage.value),
// 被监听的状态数组,这些状态变化将会触发一次请求
[currentPage],
{
// ⚠️调用useWatcher默认不触发,注意和useRequest的区别
// 手动设置immediate为true可以初始获取第1页数据
immediate: true
}
);
</script>
import { useState } from 'react';
// method实例创建函数
const getTodoList = currentPage => {
return alovaInstance.Get('/todo/list', {
params: {
currentPage,
pageSize: 10
}
});
};
const App = () => {
const [currentPage, setCurrentPage] = useState(1);
const {
loading,
data,
error
// 第一个参数为返回method实例的函数,而非method实例本身
} = useWatcher(
() => getTodoList(currentPage),
// 被监听的状态数组,这些状态变化将会触发一次请求
[currentPage],
{
// ⚠️调用useWatcher默认不触发,注意和useRequest的区别
// 手动设置immediate为true可以初始获取第1页数据
immediate: true
}
);
return {
/* ... */
};
};
<script>
import { writable } from 'svelte/store';
// method实例创建函数
const getTodoList = currentPage => {
return alovaInstance.Get('/todo/list', {
params: {
currentPage,
pageSize: 10
}
});
};
const currentPage = writable(1);
const {
loading,
data,
error
// 第一个参数为返回method实例的函数,而非method实例本身
} = useWatcher(
() => getTodoList($currentPage),
// 被监听的状态数组,这些状态变化将会触发一次请求
[currentPage],
{
// ⚠️调用useWatcher默认不触发,注意和useRequest的区别
// 手动设置immediate为true可以初始获取第1页数据
immediate: true
}
);
</script>
<!-- ... -->
<template>
<!-- ... -->
</template>
<script>
import { mapAlovaHook } from '@alovajs/vue-options';
// method实例创建函数
const getTodoList = currentPage => {
return alovaInstance.Get('/todo/list', {
params: {
currentPage,
pageSize: 10
}
});
};
export default {
mixins: mapAlovaHook(function () {
paging: useWatcher(
() => getTodoList(this.currentPage),
// 被监听的状态数组,这些状态变化将会触发一次请求
['currentPage'],
{
// ⚠️调用useWatcher默认不触发,注意和useRequest的区别
// 手动设置immediate为true可以初始获取第1页数据
immediate: true
}
);
}),
data() {
return {
currentPage: 1
};
}
};
</script>