Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply VueUse composables in Vue 3/Nuxt projects to replace custom implementations with battle-tested utilities.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/from.md
1---2category: '@RxJS'3---45# from / fromEvent67Wrappers around RxJS's [`from()`](https://rxjs.dev/api/index/function/from) and [`fromEvent()`](https://rxjs.dev/api/index/function/fromEvent) to allow them to accept `ref`s.89## Usage1011<!-- TODO: import rxjs error if enable twoslash -->1213```ts no-twoslash14import { from, fromEvent, toObserver, useSubscription } from '@vueuse/rxjs'15import { interval } from 'rxjs'16import { map, mapTo, takeUntil, withLatestFrom } from 'rxjs/operators'17import { shallowRef, useTemplateRef } from 'vue'1819const count = shallowRef(0)20const button = useTemplateRef('buttonRef')2122useSubscription(23interval(1000)24.pipe(25mapTo(1),26takeUntil(fromEvent(button, 'click')),27withLatestFrom(from(count, {28immediate: true,29deep: false,30})),31map(([curr, total]) => curr + total),32)33.subscribe(toObserver(count)), // same as ).subscribe(val => (count.value = val))34)35```3637## from3839The `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.4041### Watch Options4243When using `from` with a ref, you can pass Vue's `WatchOptions`:4445| Option | Type | Description |46| ----------- | --------------------------- | ---------------------------------- |47| `immediate` | `boolean` | Emit the current value immediately |48| `deep` | `boolean` | Deeply watch nested objects |49| `flush` | `'pre' \| 'post' \| 'sync'` | Timing of the callback flush |5051## fromEvent5253The `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.5455```ts no-twoslash56import { fromEvent, useSubscription } from '@vueuse/rxjs'57import { useTemplateRef } from 'vue'5859const button = useTemplateRef('buttonRef')6061// Will automatically subscribe when the button element becomes available62useSubscription(63fromEvent(button, 'click').subscribe(() => {64console.log('clicked!')65})66)67```6869## Type Declarations7071```ts72export declare function from<T>(73value: ObservableInput<T> | Ref<T>,74watchOptions?: WatchOptions,75): Observable<T>76export declare function fromEvent<T extends HTMLElement | null>(77value: MaybeRef<T>,78event: string,79): Observable<Event>80```81