VueHooks Plus

2.4.3 · active · verified Sun Apr 19

VueHooks Plus is a high-performance and simple library offering a comprehensive collection of Vue 3 composition API hooks. It is currently stable at version 2.4.3 and demonstrates an active development cadence with frequent minor and patch releases. Key differentiators include its robust `useRequest` hook for powerful request management, full TypeScript support with predictable static types, SSR compatibility, and support for on-demand loading and auto-imports via resolvers like `@vue-hooks-plus/resolvers`. The library aims to provide a rich set of utilities for common Vue development patterns, promoting reusability and simplifying complex logic within Vue 3 applications.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to use the `useRequest` hook to fetch data, handle loading and error states, and dynamically change parameters, including polling.

import { ref } from 'vue'
import { useRequest } from 'vue-hooks-plus'

interface UserData {
  id: number;
  name: string;
  email: string;
}

// Simulate an API call
const fetchUser = async (userId: number): Promise<UserData> => {
  console.log(`Fetching user with ID: ${userId}`)
  await new Promise(resolve => setTimeout(resolve, 1000))
  if (userId === 1) {
    return { id: 1, name: 'John Doe', email: 'john@example.com' }
  } else if (userId === 2) {
    throw new Error('User not found')
  } else {
    return { id: userId, name: `User ${userId}`, email: `user${userId}@example.com` }
  }
}

// A basic Vue component using useRequest
export default {
  setup() {
    const currentUserId = ref(1)

    const { data, loading, error, run, cancel } = useRequest(
      () => fetchUser(currentUserId.value),
      {
        refreshDeps: [currentUserId],
        pollingInterval: 5000, // Poll every 5 seconds
        manual: false, // Automatically run on mount/deps change
        onError: (e) => console.error('Request error:', e.message)
      }
    )

    const fetchNextUser = () => {
      currentUserId.value++
    }

    return {
      data,
      loading,
      error,
      fetchNextUser,
      cancel,
      currentUserId
    }
  },
  template: `
    <div>
      <h1>User Data with useRequest</h1>
      <p>Current User ID: {{ currentUserId }}</p>
      <div v-if="loading">Loading user...</div>
      <div v-else-if="error">Error: {{ error.message }}</div>
      <div v-else-if="data">
        <p>ID: {{ data.id }}</p>
        <p>Name: {{ data.name }}</p>
        <p>Email: {{ data.email }}</p>
      </div>
      <button @click="fetchNextUser">Fetch Next User</button>
      <button @click="cancel">Cancel Request</button>
    </div>
  `
}

view raw JSON →