@vueuse/rxjs
這是 VueUse 的附加元件,能夠以更自然的方式使用 RxJS。
安裝
bash
npm i @vueuse/rxjs rxjs
函式
from
— RxJSfrom()
和fromEvent()
的封裝器,使其能夠接受ref
toObserver
— 將ref
轉換為 RxJS Observer 的 sugar 函式useExtractedObservable
— 使用從一個或多個 composable 提取的 RxJSObservable
useObservable
— 使用 RxJSObservable
useSubject
— 將 RxJSSubject
綁定到ref
並雙向傳播數值變更useSubscription
— 使用 RxJSSubscription
,無需擔心取消訂閱或造成記憶體洩漏watchExtractedObservable
— 監看從一個或多個 composable 提取的 RxJSObservable
的數值
範例
ts
import { from, fromEvent, useObservable } from '@vueuse/rxjs'
import { forkJoin, of } from 'rxjs'
import { ajax } from 'rxjs/ajax'
import { concatAll, map, mergeMap, pluck, scan, take } from 'rxjs/operators'
import { ref } from 'vue'
const BASE_URL = 'https://jsonplaceholder.typicode.com'
const button = ref<HTMLButtonElement>(null)
const posts = useObservable(
fromEvent(button, 'click').pipe(
mergeMap(() => ajax.getJSON(`${BASE_URL}/posts`).pipe(
concatAll(),
take(4),
mergeMap(({ id, userId, title }) => forkJoin({
id: of(id),
comments: ajax.getJSON(`${BASE_URL}/posts/${id}/comments`).pipe(
map(comments => comments.length),
),
username: ajax.getJSON(`${BASE_URL}/users/${userId}`).pipe(
pluck('username'),
),
}), 2),
scan((acc, curr) => [...acc, curr], []),
)),
),
)
授權條款
MIT 授權條款 © 2019-現在 Anthony Fu