Skip to content

来自/来自事件

🌐 from / fromEvent

围绕 RxJS 的 from()fromEvent() 的封装,使它们可以接受 ref

🌐 Wrappers around RxJS's from() and fromEvent() to allow them to accept refs. Available in the @vueuse/rxjs add-on.

用法

🌐 Usage

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)), // same as ).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)),
)

from

类别
导出大小
122 B
@vueuse/rxjs
最近修改
2 days ago

from 函数可以接收标准的 RxJS ObservableInput 或 Vue ref。当传入一个 ref 时,它会创建一个 Observable,每当 ref 的值改变时就会发出对应的值。

🌐 The from function can accept either a standard RxJS ObservableInput or a Vue ref. When passed a ref, it creates an Observable that emits whenever the ref's value changes.

监视选项

🌐 Watch Options

在使用带有 ref 的 from 时,你可以传入 Vue 的 WatchOptions

🌐 When using from with a ref, you can pass Vue's WatchOptions:

选项类型描述
immediateboolean立即触发当前值
deepboolean深度监听嵌套对象
flush'pre' | 'post' | 'sync'回调刷新时机

fromEvent

fromEvent 函数扩展了 RxJS 的 fromEvent,以接受对元素的引用。当引用的值发生变化时(例如,组件挂载后),它会自动订阅新的元素。

🌐 The fromEvent function extends RxJS's fromEvent to accept a ref to an element. When the ref's value changes (e.g., after the component mounts), it automatically subscribes to the new element.

ts
import { fromEvent, useSubscription } from '@vueuse/rxjs'
import { useTemplateRef } from 'vue'

const button = useTemplateRef('buttonRef')

// Will automatically subscribe when the button element becomes available
useSubscription(
  fromEvent(button, 'click').subscribe(() => {
    console.log('clicked!')
  })
)