### Install Fluth-Vue
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/guide/quick.en.md
Installs the fluth-vue package using pnpm. This is the initial step to begin using the library.
```bash
pnpm install fluth-vue
```
--------------------------------
### Install Fluth-Vue
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/guide/quick.cn.md
Installs the fluth-vue package using pnpm. This is the initial step to begin using the library in your project.
```bash
pnpm install fluth-vue
```
--------------------------------
### Install fluth-vue
Source: https://github.com/fluthjs/fluth-vue/blob/master/README.cn.md
Instructions for installing the fluth-vue library using npm, yarn, or pnpm.
```bash
npm install fluth-vue
# 或者
yarn add fluth-vue
# 或者
pnpm add fluth-vue
```
--------------------------------
### User Information Cache Example
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/cache.en.md
An example of caching user information for 30 minutes using `useFetch` with a specified expiration and URL-based cache resolution.
```javascript
const { data: userInfo } = useFetch("/api/user", {
cacheSetting: {
expiration: 1000 * 60 * 30, // 30 minutes
cacheResolve: ({ url }) => url,
},
}).json();
```
--------------------------------
### Install fluth-vue with npm, yarn, or pnpm
Source: https://github.com/fluthjs/fluth-vue/blob/master/README.md
This snippet shows the commands to install the fluth-vue library using different package managers: npm, yarn, and pnpm.
```bash
npm install fluth-vue
# or
yarn add fluth-vue
# or
pnpm add fluth-vue
```
--------------------------------
### Create a Stream with Fluth-Vue
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/guide/quick.en.md
Demonstrates how to create a reactive stream using the '$()' function from 'fluth-vue'. This stream holds the initial state for a form.
```vue
```
--------------------------------
### Cache Key Generation Examples
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/cache.en.md
Provides examples of `cacheResolve` functions for generating cache keys based on different request parameters like URL, payload, method, and type.
```javascript
// Cache based on URL
cacheResolve: ({ url }) => url;
```
```javascript
// Cache based on URL and payload
cacheResolve: ({ url, payload }) => url + JSON.stringify(payload);
```
```javascript
// Cache based on complete request configuration
cacheResolve: ({ url, payload, method, type }) =>
`${method}:${url}:${type}:${JSON.stringify(payload)}`;
```
--------------------------------
### 响应式更新:GET 参数 Ref 更新触发请求 (Vue)
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/refresh.cn.md
当 GET 请求的参数使用 ref 定义并发生变化时,useFetch 会自动更新 URL 并触发新的请求。这使得 GET 请求的查询参数能够响应式地更新。
```typescript
import { ref } from "vue";
import { useFetch } from "fluth-vue";
const payload = ref({ id: 1 });
const { data } = useFetch("https://example.com", { refetch: true })
.get(payload)
.json();
payload.value.id = 2; // ✅ 触发新请求: https://example.com?id=2
```
--------------------------------
### Creating Custom Fetch Instances
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/use.cn.md
Demonstrates how to create reusable `useFetch` instances with pre-configured options like `baseUrl` and interceptors using `createFetch`.
```TypeScript
const useMyFetch = createFetch({
baseUrl: "https://my-api.com",
options: {
mode: "cors",
async beforeFetch({ options }) {
const myToken = await getMyToken();
options.headers.Authorization = `Bearer ${myToken}`;
return { options };
},
},
});
const { loading, error, data } = useMyFetch("users");
```
--------------------------------
### Basic useFetch Usage
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/use.cn.md
Demonstrates the fundamental usage of the `useFetch` hook by providing a URL. It shows how to access loading, error, and data states.
```TypeScript
import { useFetch } from "fluth-vue";
const { loading, error, data } = useFetch(url);
```
--------------------------------
### 响应式更新:GET 参数 Reactive 更新触发请求 (Vue)
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/refresh.cn.md
使用 reactive 定义的 GET 请求参数对象,当其属性变化时,useFetch 会自动更新 URL 并触发请求。这提供了对 GET 请求查询参数的响应式控制。
```typescript
import { reactive } from "vue";
import { useFetch } from "fluth-vue";
const payload = reactive({ id: 1 });
const { data } = useFetch("https://example.com", { refetch: true })
.get(payload)
.json();
payload.id = 2; // ✅ 触发新请求: https://example.com?id=2
```
--------------------------------
### UseFetchReturn HTTP Methods (get, post, put, delete, patch, head, options)
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/api.en.md
Outlines the various HTTP method functions (get, post, put, delete, patch, head, options) provided by UseFetchReturn for making different types of requests. Each method accepts optional payloads and content types.
```typescript
get: (
payload?: MaybeRefOrGetter | Stream | Observable,
) => UseFetchResult;
post: (
payload?: MaybeRefOrGetter | Observable | Stream,
type?: string,
) => UseFetchResult;
put: (
payload?: MaybeRefOrGetter | Observable | Stream,
type?: string,
) => UseFetchResult;
delete: (
payload?: MaybeRefOrGetter | Observable | Stream,
type?: string,
) => UseFetchResult;
patch: (
payload?: MaybeRefOrGetter | Observable | Stream,
type?: string,
) => UseFetchResult;
head: (
payload?: MaybeRefOrGetter | Observable | Stream,
type?: string,
) => UseFetchResult;
options: (
payload?: MaybeRefOrGetter | Observable | Stream,
type?: string,
) => UseFetchResult;
```
--------------------------------
### Setting Request Method and Response Type
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/use.cn.md
Shows how to specify the HTTP request method (e.g., GET, POST) and the expected response data type (e.g., JSON, text, blob) using chained methods or options.
```TypeScript
// Request will be sent using GET method, data will be parsed as JSON
const { data } = useFetch(url).get().json();
// Request will be sent using POST method, data will be parsed as text
const { data } = useFetch(url).post().text();
// Or using options to set the method
// Request will be sent using GET method, data will be parsed as blob
const { data } = useFetch(url, { method: "GET" }, { refetch: true }).blob();
```
--------------------------------
### Basic Throttle Example
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/throttle.en.md
Illustrates basic throttle usage by setting a wait time of 1000ms, ensuring the execute function is called at most once per second.
```javascript
const { execute } = useFetch(url, {
immediate: false,
throttle: 1000, // Execute at most once per second
});
// Frequent calls, but execute at most once per second
execute(); // ✅ Execute immediately
execute(); // ❌ Ignored by throttle
execute(); // ❌ Ignored by throttle
// Can execute again after 1 second
```
--------------------------------
### Create a Stream with Initial Value (Vue)
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/guide/quick.cn.md
Demonstrates creating a reactive stream using the `$` function from 'fluth-vue' with an initial state object. This stream can be used to manage component state.
```vue
```
--------------------------------
### Render Stream in Vue Template with Fluth-Vue
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFluth/index.en.md
Illustrates how to integrate Fluth-Vue's render$ functionality within a Vue.js template. This example shows setting the script language to 'tsx', defining the render$ methods in the setup, and then rendering these streams using the `` syntax. It mirrors the TSX example's functionality, demonstrating reactive updates without affecting the parent component's lifecycle.
```vue
User Information
Order Information
```
--------------------------------
### Add Form Logic and API Integration (Vue)
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/guide/quick.cn.md
Illustrates adding form input handling and submission logic. It uses `@input` to update the stream and demonstrates integrating with `useFetch` for API calls, including debouncing and validation.
```vue
```
--------------------------------
### Vue Usage Example with fluth-vue Streams
Source: https://github.com/fluthjs/fluth-vue/blob/master/README.md
This example demonstrates how to use fluth-vue in a Vue 3 application. It initializes a stream, pipes it through debounce, map, and filter operations, and updates the stream value on button click. It showcases reactive stream rendering within the Vue template.
```vue
{{ stream$ }}
{{ tips$ }}
```
--------------------------------
### 响应式更新:GET 参数 Stream 更新触发请求 (Vue)
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/refresh.cn.md
通过 Stream 或 Observable 更新 GET 请求的参数,useFetch 会在 Stream 发出新值时自动更新 URL 并触发请求。这适用于需要异步更新 GET 参数的情况。
```typescript
import { $ } from "fluth-vue";
import { useFetch } from "fluth-vue";
const payload = $("https://example.com");
const { data } = useFetch("https://example.com", { refetch: true })
.get(payload)
.json();
payload.next({ id: 2 }); // ✅ 触发新请求: https://example.com?id=2
```
--------------------------------
### Handling Fetch Events
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/use.cn.md
Shows how to use `onFetchResponse` and `onFetchError` to execute callbacks when a fetch request receives a response or encounters an error, respectively.
```TypeScript
const { onFetchResponse, onFetchError } = useFetch(url);
onFetchResponse((response) => {
console.log(response.status);
});
onFetchError((error) => {
console.error(error.message);
});
```
--------------------------------
### Cache User Information (JavaScript)
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/cache.cn.md
An example of caching user information for 30 minutes, using the URL as the cache key.
```javascript
const { data: userInfo } = useFetch("/api/user", {
cacheSetting: {
expiration: 1000 * 60 * 30, // 30分钟
cacheResolve: ({ url }) => url,
},
}).json();
```
--------------------------------
### Form Submission Logic with Fluth-Vue
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/guide/quick.en.md
Implements form submission logic using Fluth-Vue streams, including debouncing, validation, and making an API call via `useFetch`. It demonstrates piping streams for complex asynchronous operations.
```vue
```
--------------------------------
### Basic Throttle Example
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/throttle.cn.md
Illustrates the basic usage of the throttle option to limit the execution frequency of `useFetch`. Calls to `execute()` are made, but only one will succeed within the specified throttle interval.
```javascript
const { execute } = useFetch(url, {
immediate: false,
throttle: 1000, // 每秒最多执行一次
});
// 频繁调用,但每秒最多执行一次
execute(); // ✅ 立即执行
execute(); // ❌ 被节流忽略
execute(); // ❌ 被节流忽略
// 1 秒后可以再次执行
```
--------------------------------
### Basic Debounce Example
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/debounce.en.md
Illustrates basic debounce functionality by setting a 300ms delay. Rapid calls to execute() will result in only the last call being processed after the delay.
```javascript
const { execute } = useFetch(url, {
immediate: false,
debounce: 300, // 300ms debounce
});
// Rapid consecutive calls, only the last one will execute
execute();
execute();
execute(); // ✅ Only this one will execute after 300ms
```
--------------------------------
### Asynchronous useFetch Usage
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/use.cn.md
Illustrates how to use `useFetch` asynchronously, similar to a standard fetch call. It requires wrapping the component in `` if the component is asynchronous.
```TypeScript
import { useFetch } from "fluth-vue";
const { loading, error, data } = await useFetch(url);
```
--------------------------------
### Custom Instance Interceptor Combination
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/use.cn.md
Explains how to control the behavior of interceptors (`beforeFetch`, `afterFetch`, `onFetchError`) between pre-configured and newly generated instances using the `combination` option ('overwrite' or 'chaining').
```TypeScript
const useMyFetch = createFetch({
baseUrl: "https://my-api.com",
combination: "overwrite",
options: {
// The pre-configured instance's beforeFetch will only run if the newly generated instance does not pass a beforeFetch
async beforeFetch({ options }) {
const myToken = await getMyToken();
options.headers.Authorization = `Bearer ${myToken}`;
return { options };
},
},
});
// Using the beforeFetch from useMyFetch
const { loading, error, data } = useMyFetch("users");
// Using a custom beforeFetch
const { loading, error, data } = useMyFetch("users", {
async beforeFetch({ url, options, cancel }) {
const myToken = await getMyToken();
if (!myToken) cancel();
options.headers = {
...options.headers,
Authorization: `Bearer ${myToken}`,
};
return { options };
},
});
```
--------------------------------
### Automatic Refetching with URL Changes
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/use.cn.md
Shows how to configure `useFetch` to automatically re-trigger requests when a URL ref changes. The `refetch: true` option enables this behavior.
```TypeScript
const url = ref("https://my-api.com/user/1");
const { data } = useFetch(url, { refetch: true });
url.value = "https://my-api.com/user/2"; // Will trigger another request
```
--------------------------------
### Implement Fluth-Vue Service B
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/guide/pinia.en.md
Details the implementation of 'useServiceB', another fluth-vue service. This example demonstrates accessing streams from a dependent service ('serviceA') and creating new streams, including using 'promiseAll' for concurrent stream processing.
```typescript
// Define business service B
const useServiceB = (serviceA: ReturnType) => {
const { dataA$ } = serviceA;
const dataC$ = $("C");
const dataD$ = $(3);
dataC$.then((dataC) => {
// Detailed logic
});
promiseAll(dataA$, dataD$).then(([dataA, dataD]) => {
// Detailed logic
});
return {
dataC$,
dataD$,
};
};
```
--------------------------------
### Print Entire Stream Data
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/guide/debug.en.md
This example shows how to print the entire stream using the `consoleAll` plugin from `fluth-vue`. It includes piping the stream through `debounce` and handling potential errors in subsequent `.then` calls, demonstrating how to observe all stream events.
```typescript
import { $, consoleAll } from "fluth-vue";
const data$ = $().use(consoleAll());
data$
.pipe(debounce(300))
.then((value) => {
throw new Error(value + 1);
})
.then(undefined, (error) => ({ current: error.message }));
```
--------------------------------
### Basic useFetch Usage
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/introduce.cn.md
Demonstrates the basic import and usage of the useFetch composable from 'fluth-vue'. It shows how to initiate a fetch request to a given URL and access the returned data, loading state, error state, and the promise observable.
```javascript
import { useFetch } from "fluth-vue";
const { data, loading, error, promise$ } = useFetch("https://example.com");
```
--------------------------------
### Declarative + Reactive Relationship with useFetch
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/introduce.cn.md
Illustrates how to create a declarative and reactive relationship between data sources using useFetch. The example shows a composable function `useFetchApi` that takes a payload ref and returns data that reactively updates based on the payload changes, with automatic refetching enabled.
```typescript
import { useFetch } from "fluth-vue";
const useFetchApi = (payload: Ref>) =>
useFetch("https://example.com", { refetch: true }).post(payload).json();
const data1 = ref({ a: 1 });
// 使用
const { data: data2 } = useFetchApi(data1);
```
--------------------------------
### useFetch get Method
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/api.cn.md
The 'get' method configures the fetch request to use the HTTP GET method. It accepts an optional payload which can be a Ref, Getter, Stream, or Observable, and returns a UseFetchResult.
```typescript
type get: (payload?: MaybeRefOrGetter | Stream | Observable) => UseFetchResult;
```
--------------------------------
### Configure Request Initialization Options
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/api.en.md
Defines the structure for RequestInit, inheriting properties like body, cache, credentials, headers, method, mode, and signal for request configuration.
```typescript
interface RequestInit {
/** A BodyInit object or null to set request's body. */
body?: BodyInit | null;
/** A string indicating how the request will interact with the browser's cache to set request's cache. */
cache?: RequestCache;
/** A string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. Sets request's credentials. */
credentials?: RequestCredentials;
/** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */
headers?: HeadersInit;
/** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */
integrity?: string;
/** A boolean to set request's keepalive. */
keepalive?: boolean;
/** A string to set request's method. */
method?: string;
/** A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request's mode. */
mode?: RequestMode;
priority?: RequestPriority;
/** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */
redirect?: RequestRedirect;
/** A string whose value is a same-origin URL, "about:client", or the empty string, to set request's referrer. */
referrer?: string;
/** A referrer policy to set request's referrerPolicy. */
referrerPolicy?: ReferrerPolicy;
/** An AbortSignal to set request's signal. */
signal?: AbortSignal | null;
/** Can only be null. Used to disassociate request from any Window. */
window?: null;
}
```
--------------------------------
### Reactive GET Parameter Updates with useFetch
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/refresh.en.md
Illustrates how to trigger new GET requests when query parameters change. Supports ref, reactive, and Stream/Observable types for the parameters.
```typescript
import { ref, reactive } from "vue";
import { useFetch } from "fluth-vue";
const url = "https://example.com";
// Using ref for parameters
const paramsRef = ref({ id: 1 });
const { data: dataRef } = useFetch(url, { refetch: true }).get(paramsRef).json();
paramsRef.value.id = 2; // ✅ Triggers new request: https://example.com?id=2
// Using reactive for parameters
const paramsReactive = reactive({ id: 1 });
const { data: dataReactive } = useFetch(url, { refetch: true }).get(paramsReactive).json();
paramsReactive.id = 2; // ✅ Triggers new request: https://example.com?id=2
```
```javascript
import { $, useFetch } from "fluth-vue";
const url = "https://example.com";
const paramsStream = $("https://example.com", { id: 1 });
const { data } = useFetch(url, { refetch: true }).get(paramsStream).json();
paramsStream.next({ id: 2 }); // ✅ Triggers new request: https://example.com?id=2
```
--------------------------------
### Vue UseFetch GET Method
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/api.en.md
Sets the fetch request method to GET and appends the payload as query parameters to the URL. Supports reactive data, Observables, and Streams as payload.
```typescript
type get: (payload?: MaybeRefOrGetter | Stream | Observable) => UseFetchResult;
```
--------------------------------
### Create Vue UseFetch Instance
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/api.en.md
Creates a new instance of `useFetch` with predefined configuration options, such as a base URL or request combination strategy.
```typescript
interface CreateFetchOptions {
baseUrl?: MaybeRefOrGetter;
combination?: "overwrite" | "chain";
options?: UseFetchOptions;
}
declare function createFetch(config?: CreateFetchOptions): typeof useFetch;
```
--------------------------------
### Vue Ref Data Modification Example
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/guide/immutable.en.md
Provides a standard Vue.js example using `ref` to manage reactive state. It demonstrates incrementing a nested property and includes a watcher to log changes to the console.
```vue
```
--------------------------------
### Basic useFetch Usage
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/introduce.en.md
Demonstrates the basic usage of the useFetch composable to fetch data from a given URL. It returns data, loading state, error state, and a promise observable.
```javascript
import { useFetch } from "fluth-vue";
const { data, loading, error, promise$ } = useFetch("https://example.com");
```
--------------------------------
### Project Structure for Fluth-Vue Logic Layer
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/guide/pinia.cn.md
This snippet illustrates the recommended directory structure for the logical layer in a Fluth-Vue project using Pinia. It shows how to organize business modules and their associated services.
```javascript
└── store
├── index.ts
│
├── useModuleA
│ │ ├── services
│ │ │ ├── useServiceA.ts
│ │ │ └── useServiceB.ts
│ │ │ └── ...
│ │ └── index.ts
│ │
│ └── useModuleB
│ │ ├── services
│ │ │ ├── useServiceC.ts
│ │ │ └── useServiceD.ts
│ │ │ └── ...
│ │ └── index.ts
│ └── ...
```
--------------------------------
### TypeScript: Example usage of recover$
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFluth/index.en.md
Provides an example of using the recover$ method to convert a Vue reactive object into fluth Stream objects. It demonstrates converting properties 'a$' and 'b$' from a reactive object and then updating their values using the Stream's next method.
```typescript
const obj = reactive({
a$: $("a"),
b$: $("b"),
});
const { a$, b$ } = recover$(obj);
a$.next("c");
b$.next("d");
```
--------------------------------
### recover$ Example - Restoring Stream Properties
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFluth/index.cn.md
This example demonstrates how to use recover$ to convert a Vue reactive object containing stream properties back into fluth Stream objects. It shows the process of creating a reactive object with fluth streams and then using recover$ to extract and manipulate these streams, highlighting the correct usage for properties that were originally streams.
```typescript
const obj = reactive({
a$: $("a"),
b$: $("b"),
});
const { a$, b$ } = recover$(obj);
a$.next("c");
b$.next("d");
```
--------------------------------
### useFetch Options: initialData
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/api.en.md
Configures the initial data to be used before the fetch request completes. Defaults to null.
```typescript
initialData?: any;
```
--------------------------------
### effect$ Example - Handling User and Order Data Updates
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFluth/index.cn.md
This example demonstrates the use of effect$ in a Vue component to manage and display user and order information. It utilizes fluth-vue's stream capabilities ($) to create reactive data objects and updates them using the set method. The effect$ function ensures that the rendered output is updated efficiently when the stream data changes, without triggering unnecessary component re-renders.
```tsx
import { defineComponent, onUpdated } from "vue";
import { $, effect$ } from "fluth-vue";
export default defineComponent(
() => {
const user$ = $({ name: "", age: 0, address: "" });
const order$ = $({ item: "", price: 0, count: 0 });
onUpdated(() => {
console.log("Example 组件更新");
});
return effect$(() => (
);
},
{
name: "Example",
},
);
```
--------------------------------
### Basic fluth Stream Usage
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/guide/motion.en.md
Demonstrates the creation and manipulation of fluth streams. It shows how to initialize a stream with data, derive new streams using 'thenImmediate', and update stream values. This example highlights fluth's ability to hold state and react to changes, serving as an alternative to Vue's ref or reactive.
```typescript
import { $ } from "fluth";
const userInfo$ = $({ name: "fluth", age: 18, role: "admin" });
const isAdult$ = userInfo$.thenImmediate((value) => value.age >= 18);
const isAdmin$ = userInfo$.thenImmediate((value) => value.role === "admin");
userInfo$.value; // { name: "fluth", age: 18, role: "admin" }
isAdult$.value; // true
isAdmin$.value; // true
userInfo$.set((value) => {
value.age = 17;
value.role = "user";
});
userInfo$.value; // { name: "fluth", age: 17, role: "user" }
isAdult$.value; // false
isAdmin$.value; // false
```
--------------------------------
### useFetch Options: immediate
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/api.en.md
Determines whether the fetch request should execute automatically when the useFetch composable is initialized. Defaults to true.
```typescript
immediate?: boolean;
```
--------------------------------
### 响应式更新:URL 变化触发请求 (Vue)
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/refresh.cn.md
通过将 URL 参数设置为 ref,当 URL 的值发生变化时,useFetch 会自动触发新的请求。这对于需要根据用户交互或其他状态动态更改请求 URL 的场景非常有用。
```typescript
import { ref } from "vue";
import { useFetch } from "fluth-vue";
const url = ref("https://my-api.com/user/1");
const { data } = useFetch(url, { refetch: true }).get().json();
url.value = "https://my-api.com/user/2"; // ✅ 触发新请求
```
--------------------------------
### Automatic Request Abort with Timeout
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/use.cn.md
Shows how to automatically abort a `useFetch` request after a specified timeout duration using the `timeout` option.
```TypeScript
const { data } = useFetch(url, { timeout: 100 });
```
--------------------------------
### Configure Request Initialization Options in Vue
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/api.cn.md
Defines the structure for `RequestInit`, which includes standard browser fetch options like body, cache, credentials, headers, method, and more. `UseFetchOptions` inherits all these properties, allowing for comprehensive request customization.
```typescript
interface RequestInit {
/** A BodyInit object or null to set request's body. */
body?: BodyInit | null;
/** A string indicating how the request will interact with the browser's cache to set request's cache. */
cache?: RequestCache;
/** A string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. Sets request's credentials. */
credentials?: RequestCredentials;
/** A Headers object, an object literal, or an array of two-item arrays to set request's headers. */
headers?: HeadersInit;
/** A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */
integrity?: string;
/** A boolean to set request's keepalive. */
keepalive?: boolean;
/** A string to set request's method. */
method?: string;
/** A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request's mode. */
mode?: RequestMode;
priority?: RequestPriority;
/** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */
redirect?: RequestRedirect;
/** A string whose value is a same-origin URL, "about:client", or the empty string, to set request's referrer. */
referrer?: string;
/** A referrer policy to set request's referrerPolicy. */
referrerPolicy?: ReferrerPolicy;
/** An AbortSignal to set request's signal. */
signal?: AbortSignal | null;
/** Can only be null. Used to disassociate request from any Window. */
window?: null;
}
```
--------------------------------
### UseFetchOptions Interface
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/api.cn.md
Details the `UseFetchOptions` interface, which extends `RequestInit` and includes various configurations for fetch requests such as initial data, immediate execution, conditional fetching, refetching, caching, debouncing, and callbacks.
```typescript
interface UseFetchOptions extends RequestInit {
/**
* Initial data before the request finished
*
* @default null
*/
initialData?: any;
/**
* Will automatically run fetch when `useFetch` is used
*
* @default true
*/
immediate?: boolean;
/**
* execute fetch only when condition is true
* @default true
*/
condition?:
| MaybeRefOrGetter
| Observable
| Stream
| (() => boolean);
/**
* Will automatically refetch when:
* - the URL is changed if the URL is a ref
* - the payload is changed if the payload is a ref
*
* @default false
*/
refetch?: boolean;
/**
* Auto refetch interval in millisecond
* @default undefined
*/
refresh?: number;
/**
* Allow cache the request result and reuse it if cacheResolve result is same
*
* @default undefined
*/
cacheSetting?: {
expiration?: number;
cacheResolve?: (config: InternalConfig & { url: string }) => string;
};
/**
* Debounce interval in millisecond
*
* @default undefined
*/
debounce?:
| number
| {
wait: number;
options?: {
leading?: boolean;
maxWait?: number;
trailing?: boolean;
};
};
/**
* Throttle interval in millisecond
*
* @default undefined
*/
throttle?:
| number
| {
wait: number;
options?: {
leading?: boolean;
trailing?: boolean;
};
};
/**
* Indicates if the fetch request has finished
*/
isFinished?: boolean;
/**
* Timeout for abort request after number of millisecond
* `0` means use browser default
*
* @default undefined
*/
timeout?: number;
/**
* Fetch function
*/
fetch?: typeof window.fetch;
/**
* Allow update the data ref when fetch error whenever provided, or mutated in the onFetchError callback
*
* @default false
*/
updateDataOnError?: boolean;
/**
* Will run immediately before the fetch request is dispatched
*/
beforeFetch?: (
ctx: BeforeFetchContext,
) =>
| Promise | void>
| Partial
| void;
/**
* Will run immediately after the fetch request is returned.
* Runs after any 2xx response
*/
afterFetch?: (
ctx: AfterFetchContext,
) => Promise> | Partial;
/**
* Will run immediately after the fetch request is returned.
* Runs after any 4xx and 5xx response
*/
onFetchError?: (ctx: {
data: any;
response: Response | null;
error: any;
}) => Promise> | Partial;
}
```
--------------------------------
### Intercepting Response Data with afterFetch
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/use.cn.md
Demonstrates the use of the `afterFetch` option to intercept and modify response data before it updates the component's state.
```TypeScript
const { data } = useFetch(url, {
afterFetch(ctx) {
if (ctx.data.title === "HxH") ctx.data.title = "Hunter x Hunter"; // Modify response data
return ctx;
},
});
```
--------------------------------
### Basic useFetch Usage
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/use.en.md
Demonstrates the fundamental usage of the `useFetch` function by providing a URL. It shows how to access loading, error, and data states.
```TypeScript
import { useFetch } from "fluth-vue";
const { loading, error, data } = useFetch(url);
```
--------------------------------
### Aborting Fetch Requests
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/use.cn.md
Demonstrates how to abort an ongoing `useFetch` request using the `abort` function. The `canAbort` property indicates if the request can be aborted.
```TypeScript
const { abort, canAbort } = useFetch(url);
setTimeout(() => {
if (canAbort.value) abort();
}, 100);
```
--------------------------------
### Provide Custom Fetch Implementation
Source: https://github.com/fluthjs/fluth-vue/blob/master/packages/core/useFetch/docs/api.en.md
Allows for the use of a custom fetch function, replacing the default window.fetch.
```typescript
type fetch = typeof window.fetch;
```