Ahooks Vue
ahooks-vue is a comprehensive collection of Vue Composition API hooks, designed to simplify common logic and stateful operations in Vue 2 (specifically 2.7+) and Vue 3 applications. Many of its hooks are direct ports and adaptations from the popular React hooks library, ahooks, offering a familiar API for developers transitioning or working across both ecosystems. Currently at version 0.15.1, the library sees a consistent, though not strictly scheduled, release cadence, with minor versions frequently bringing new features and bug fixes. Its key differentiators include broad compatibility achieved through `vue-demi`, enabling a single codebase for both major Vue versions, and full TypeScript support, providing predictable static types for enhanced developer experience and code maintainability. It aims to provide a robust and production-ready set of utilities for common patterns like state management, async requests, DOM operations, and more, similar to `vue-use` but with a distinct API influence from `ahooks`.
Common errors
-
Module 'ahooks-vue' has no exported member 'useSomeRemovedHook'
cause Attempting to import a hook that has been removed or renamed in a newer version of the library.fixCheck the official documentation or release notes for available hooks. For instance, `useOLAP` was removed in v0.14.0. -
Error: axios is not defined (or similar reference error during runtime)
cause The `axios` package, a peer dependency for certain hooks like `useRequest`, has not been installed in the project.fixRun `npm install axios` or `yarn add axios` in your project directory. -
SyntaxError: Cannot use import statement outside a module
cause Attempting to use `import` syntax in a CommonJS environment without proper transpilation or configuration, indicating a mismatch in module systems.fixEnsure your project is configured for ES Modules (e.g., `"type": "module"` in `package.json` for Node.js, or a bundler like Vite/Webpack is correctly transpiling modules for browsers). If stuck with CJS, you may need dynamic `import()` or reconsider the module setup. -
[Vue warn]: Failed to resolve component: <YourComponentName>
cause While not directly an ahooks-vue error, incorrect integration of Composition API components (where ahooks-vue hooks are used) into a Vue 2 application can lead to this. It often happens if `vue-demi`'s setup is misconfigured or the component is not properly registered.fixVerify that `vue-demi` is correctly installed and configured. For Vue 2, ensure components using Composition API are registered appropriately (e.g., using `Vue.extend` or through a build setup that handles Vue 2 Composition API transpilation).
Warnings
- breaking The `useOLAP` hook has been completely removed from the library. Any code relying on this hook will break.
- gotcha While ahooks-vue aims for Vue 2 and Vue 3 compatibility, specifically it targets Vue 2.7 and above for Vue 2. Older Vue 2 versions might not be fully supported due to reliance on features backported in 2.7 or `vue-demi` limitations.
- gotcha For hooks like `useRequest` that perform HTTP requests, the `axios` library is a peer dependency and must be installed separately in your project.
- gotcha When using ahooks-vue in a TypeScript project, ensure your `tsconfig.json` is correctly configured for Vue 3 or Vue 2.7+ (e.g., `"target": "esnext"` and `"moduleResolution": "node"` or `"bundler"`).
Install
-
npm install ahooks-vue -
yarn add ahooks-vue -
pnpm add ahooks-vue
Imports
- useRequest
const useRequest = require('ahooks-vue').useRequest;import { useRequest } from 'ahooks-vue'; - useWorkerFunction
import useWorkerFunction from 'ahooks-vue';
import { useWorkerFunction } from 'ahooks-vue'; - useUrlState
import { useUrlState } from 'ahooks-vue'; - Ref
import type { Ref } from 'vue';
Quickstart
import { defineComponent, ref } from 'vue';
import { useRequest } from 'ahooks-vue';
import axios from 'axios';
interface User {
id: number;
name: string;
email: string;
}
const fetchUser = async (userId: number): Promise<User> => {
const response = await axios.get(`https://jsonplaceholder.typicode.com/users/${userId}`);
return response.data;
};
export default defineComponent({
setup() {
const userId = ref(1);
const { data, loading, error, run } = useRequest(() => fetchUser(userId.value), {
manual: true, // Prevents immediate execution on component mount
onSuccess: (result) => {
console.log('User fetched successfully:', result);
},
onError: (err) => {
console.error('Error fetching user:', err);
},
});
const fetchUserData = () => run();
return {
data,
loading,
error,
fetchUserData
};
},
template: `
<div style="padding: 20px; font-family: sans-serif;">
<h1>User Data with useRequest</h1>
<p>This demonstrates fetching user data using ahooks-vue's useRequest hook.</p>
<button @click="fetchUserData" :disabled="loading" style="padding: 10px 15px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer;">
{{ loading ? 'Loading...' : 'Fetch User (ID: 1)' }}
</button>
<div v-if="error" style="color: red; margin-top: 10px;">Error: {{ error.message }}</div>
<div v-if="data" style="background-color: #f8f9fa; padding: 15px; border-radius: 4px; margin-top: 10px;">
<p><strong>ID:</strong> {{ data.id }}</p>
<p><strong>Name:</strong> {{ data.name }}</p>
<p><strong>Email:</strong> {{ data.email }}</p>
</div>
<div v-else-if="!loading" style="margin-top: 10px; color: #6c757d;">Click the button to fetch user data.</div>
</div>
`
});