Skip to content

from / fromEvent

RxJS 的 from()fromEvent() 的包装器,使它们能够接受 ref。 Available in the @vueuse/rxjs add-on.

用法

ts
import { from, fromEvent, toObserver, useSubscription } from '@vueuse/rxjs'
import { interval } from 'rxjs'
import { map, mapTo, takeUntil, withLatestFrom } from 'rxjs/operators'
import { shallowRef, useTemplateRef } from 'vue'

const count = shallowRef(0)
const button = useTemplateRef('buttonRef')

useSubscription(
  interval(1000)
    .pipe(
      mapTo(1),
      takeUntil(fromEvent(button, 'click')),
      withLatestFrom(from(count, {
        immediate: true,
        deep: false,
      })),
      map(([curr, total]) => curr + total),
    )
    .subscribe(toObserver(count)), // 与 ).subscribe(val => (count.value = val)) 相同
)
js
import { from, fromEvent, toObserver, useSubscription } from '@vueuse/rxjs'
import { interval } from 'rxjs'
import { map, mapTo, takeUntil, withLatestFrom } from 'rxjs/operators'
import { shallowRef, useTemplateRef } from 'vue'
const count = shallowRef(0)
const button = useTemplateRef('buttonRef')
useSubscription(
  interval(1000)
    .pipe(
      mapTo(1),
      takeUntil(fromEvent(button, 'click')),
      withLatestFrom(
        from(count, {
          immediate: true,
          deep: false,
        }),
      ),
      map(([curr, total]) => curr + total),
    )
    .subscribe(toObserver(count)),
)

类型声明

ts
export declare function 
from
<
T
>(
value
:
ObservableInput
<
T
> |
Ref
<
T
>,
watchOptions
?:
WatchOptions
,
):
Observable
<
T
>
export declare function
fromEvent
<
T
extends HTMLElement | null>(
value
:
MaybeRef
<
T
>,
event
: string,
):
Observable
<Event>

源码

源码文档

贡献者

Anthony Fu
一纸忘忧
SerKo
IlyaL
Anthony Fu
ywenhao
Robin
Ben Lesh
Amorites
rorry121
Curt Grimes
Alexander Karelas
DesselBane
yang
Michel Betancourt

更新日志

d32f8 - refactor: add @__NO_SIDE_EFFECTS__ annotations to all pure functions (#4907)
94fea - fix(fromEvent): fix type error of element reference (#4728)
7432f - feat(types): deprecate MaybeRef and MaybeRefOrGetter in favor of Vue's native (#4636)
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
fa7ed - fix(fromEvent): torn down properly (#3155)