跳至內容

@vueuse/rxjs

NPM version

這是 VueUse 的附加元件,能夠以更自然的方式使用 RxJS。

安裝

bash
npm i @vueuse/rxjs rxjs

函式

範例

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

以 MIT 授權條款發布。