• Stars
    star
    3,349
  • Rank 13,378 (Top 0.3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 9 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

👁ī¸ RxJS integration for Vue.js.

vue-rx Build Status

English | įŽ€äŊ“中文

RxJS v6+ integration for Vue.js.

BREAKING CHANGES from 5.0

  • vue-rx v6 now only works with RxJS v6+ by default. If you want to keep using RxJS v5 style code, install rxjs-compat.

Installation

NPM + ES2015

rxjs is required as a peer dependency.

npm install vue vue-rx rxjs --save
import Vue from 'vue'
import VueRx from 'vue-rx'

Vue.use(VueRx)

When bundling via webpack, dist/vue-rx.esm.js is used by default. It imports the minimal amount of Rx operators and ensures small bundle sizes.

Global Script

To use in a browser environment, use the UMD build dist/vue-rx.js. When in a browser environment, the UMD build assumes window.rxjs to be already present, so make sure to include vue-rx.js after Vue.js and RxJS. It also installs itself automatically if window.Vue is present.

Example:

<script src="https://unpkg.com/rxjs/bundles/rxjs.umd.js"></script>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="../dist/vue-rx.js"></script>

Usage

// provide Rx observables with the `subscriptions` option
new Vue({
  el: '#app',
  subscriptions: {
    msg: messageObservable
  }
})
<!-- bind to it normally in templates -->
<div>{{ msg }}</div>

The subscriptions options can also take a function so that you can return unique observables for each component instance:

import { Observable } from 'rxjs'

Vue.component('foo', {
  subscriptions: function () {
    return {
      msg: new Observable(...)
    }
  }
})

The observables are exposed as vm.$observables:

const vm = new Vue({
  subscriptions: {
    msg: messageObservable
  }
})

vm.$observables.msg.subscribe(msg => console.log(msg))

v-stream: Streaming DOM Events

vue-rx provides the v-stream directive which allows you to stream DOM events to an Rx Subject. The syntax is similar to v-on where the directive argument is the event name, and the binding value is the target Rx Subject.

<button v-stream:click="plus$">+</button>

Note that you need to declare plus$ as an instance of rxjs.Subject on the vm instance before the render happens, just like you need to declare data. You can do that right in the subscriptions function:

import { Subject } from 'rxjs'
import { map, startWith, scan } from 'rxjs/operators'

new Vue({
  subscriptions () {
    // declare the receiving Subjects
    this.plus$ = new Subject()
    // ...then create subscriptions using the Subjects as source stream.
    // the source stream emits in the format of `{ event: HTMLEvent, data?: any }`
    return {
      count: this.plus$.pipe(
        map(() => 1),
        startWith(0),
        scan((total, change) => total + change)
      )
    }
  }
})

Or, use the domStreams convenience option:

new Vue({
  // requires `Rx` passed to Vue.use() to expose `Subject`
  domStreams: ['plus$'],
  subscriptions () {
    // use this.plus$
  }
})

Finally, you can pass additional data to the stream using the alternative syntax:

<button v-stream:click="{ subject: plus$, data: someData }">+</button>

This is useful when you need to pass along temporary variables like v-for iterators. You can get the data by simply plucking it from the source stream:

const plusData$ = this.plus$.pipe(pluck('data'))

Starting in 3.1 you can also pass along extra options (passed along to native addEventListener as the 3rd argument):

<button v-stream:click="{
  subject: plus$,
  data: someData,
  options: { once: true, passive: true, capture: true }
}">+</button>

See example for actual usage.

v-stream: Streaming Custom Events from Child Components

Similar to streaming DOM events, v-stream can be used on components as well and will create observables from custom events emitted by the child component. It works similar to v-on:

<div>
  <!-- Custom component -->
  <pagination v-on:change="pageChanged()"></pagination>

  <!-- v-stream with custom component -->
  <pagination v-stream:change="pageChange$"></pagination>
</div>

Other API Methods

$watchAsObservable(expOrFn, [options])

This is a prototype method added to instances. You can use it to create an observable from a value watcher. The emitted value is in the format of { newValue, oldValue }:

import { pluck, map } from 'rxjs/operators'

const vm = new Vue({
  data: {
    a: 1
  },
  subscriptions () {
    // declaratively map to another property with Rx operators
    return {
      aPlusOne: this.$watchAsObservable('a').pipe(
        pluck('newValue'),
        map(a => a + 1)
      )
    }
  }
})

// or produce side effects...
vm.$watchAsObservable('a')
  .subscribe(
    ({ newValue, oldValue }) => console.log('stream value', newValue, oldValue),
    err => console.error(err),
    () => console.log('complete')
  )

The optional options object accepts the same options as vm.$watch.

$eventToObservable(event)

Convert vue.$on (including lifecycle events) to Observables. The emitted value is in the format of { name, msg }:

import { interval } from 'rxjs'
import { take, takeUntil } from 'rxjs/operators'

const vm = new Vue({
  created () {
    this.$eventToObservable('customEvent')
	  .subscribe((event) => console.log(event.name,event.msg))
  }
})

// vm.$once vue-rx version
this.$eventToObservable('customEvent').pipe(
  take(1)
)

// Another way to auto unsub:
let beforeDestroy$ = this.$eventToObservable('hook:beforeDestroy').pipe(take(1))

interval(500)
  .pipe(takeUntil(beforeDestroy$))

$subscribeTo(observable, next, error, complete)

This is a prototype method added to instances. You can use it to subscribe to an observable, but let VueRx manage the dispose/unsubscribe.

import { interval } from 'rxjs'

const vm = new Vue({
  mounted () {
    this.$subscribeTo(interval(1000), function (count) {
      console.log(count)
    })
  }
})

$fromDOMEvent(selector, event)

This is a prototype method added to instances. Use it to create an observable from DOM events within the instances' element. This is similar to Rx.Observable.fromEvent, but usable inside the subscriptions function even before the DOM is actually rendered.

selector is for finding descendant nodes under the component root element, if you want to listen to events from root element itself, pass null as first argument.

import { pluck } from 'rxjs/operators'

const vm = new Vue({
  subscriptions () {
    return {
      inputValue: this.$fromDOMEvent('input', 'keyup').pipe(
        pluck('target', 'value')
      )
    }
  }
})

$createObservableMethod(methodName)

Convert function calls to observable sequence which emits the call arguments.

This is a prototype method added to instances. Use it to create a shared hot observable from a function name. The function will be assigned as a vm method.

<custom-form :onSubmit="submitHandler"></custom-form>
const vm = new Vue({
  subscriptions () {
    return {
      // requires `share` operator
      formData: this.$createObservableMethod('submitHandler')
    }
  }
})

You can use the observableMethods option to make it more declarative:

new Vue({
  observableMethods: {
    submitHandler: 'submitHandler$'
    // or with Array shothand: ['submitHandler']
  }
})

The above will automatically create two things on the instance:

  1. A submitHandler method which can be bound to in template with v-on;
  2. A submitHandler$ observable which will be the stream emitting calls to submitHandler.

example

Caveats

You cannot use the watch option to watch subscriptions, because it is processed before the subscriptions are set up. But you can use $watch in the created hook instead.

Example

See /examples for some simple examples.

License

MIT

More Repositories

1

vue

This is the repo for Vue 2. For Vue 3, go to https://github.com/vuejs/core
TypeScript
207,650
star
2

awesome-vue

🎉 A curated list of awesome things related to Vue.js
71,970
star
3

core

🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript
46,527
star
4

vue-cli

🛠ī¸ webpack-based tooling for Vue.js Development
JavaScript
29,761
star
5

vuex

🗃ī¸ Centralized State Management for Vue.js.
JavaScript
28,416
star
6

devtools-v6

⚙ī¸ Browser devtools extension for debugging Vue.js applications.
TypeScript
24,600
star
7

vuepress

📝 Minimalistic Vue-powered static site generator
JavaScript
22,558
star
8

vue-router

đŸšĻ The official router for Vue 2
JavaScript
18,993
star
9

pinia

🍍 Intuitive, type safe, light and flexible Store for Vue using the composition api with DevTools support
TypeScript
13,016
star
10

vitepress

Vite & Vue powered static site generator.
TypeScript
12,445
star
11

vue-hackernews-2.0

HackerNews clone built with Vue 2.0, vue-router & vuex, with server-side rendering
JavaScript
10,957
star
12

petite-vue

6kb subset of Vue optimized for progressive enhancement
TypeScript
9,026
star
13

apollo

🚀 Apollo/GraphQL integration for VueJS
TypeScript
6,013
star
14

language-tools

⚡ High-performance Vue language tooling based-on Volar.js
TypeScript
5,830
star
15

vue-class-component

ES / TypeScript decorator for class-style Vue components.
TypeScript
5,806
star
16

vetur

Vue tooling for VS Code.
TypeScript
5,739
star
17

v2.vuejs.org

📄 Documentation for Vue 2
JavaScript
5,036
star
18

vue-loader

đŸ“Ļ Webpack loader for Vue.js components
TypeScript
4,986
star
19

rfcs

RFCs for substantial changes / feature additions to Vue core
4,862
star
20

eslint-plugin-vue

Official ESLint plugin for Vue.js
JavaScript
4,458
star
21

composition-api

Composition API plugin for Vue 2
TypeScript
4,193
star
22

router

đŸšĻ The official router for Vue.js
TypeScript
3,914
star
23

vuefire

đŸ”Ĩ Firebase bindings for Vue.js
TypeScript
3,857
star
24

create-vue

🛠ī¸ The recommended way to start a Vite-powered Vue project
Vue
3,667
star
25

vue-test-utils

Component Test Utils for Vue 2
JavaScript
3,566
star
26

docs

📄 Documentation for Vue 3
Vue
2,933
star
27

vue-touch

Hammer.js wrapper for Vue.js
JavaScript
2,723
star
28

vuex-router-sync

Effortlessly keep vue-router and vuex store in sync.
JavaScript
2,515
star
29

vue-hackernews

HackerNews clone with Vue.js
Vue
2,510
star
30

vue-vapor

Vue Vapor is a variant of Vue that offers rendering without the Virtual DOM.
TypeScript
1,909
star
31

v2.cn.vuejs.org

🇨đŸ‡ŗ Chinese translation for v2.vuejs.org
JavaScript
1,865
star
32

babel-plugin-transform-vue-jsx

babel plugin for vue 2.0 jsx
JavaScript
1,846
star
33

babel-plugin-jsx

JSX for Vue 3
TypeScript
1,713
star
34

vue-syntax-highlight

💡 Sublime Text syntax highlighting for single-file Vue components
1,485
star
35

jsx-vue2

monorepo for Babel / Vue JSX related packages
JavaScript
1,468
star
36

devtools-next

The next iteration of Vue DevTools
TypeScript
1,336
star
37

ui

đŸ’ģ UI components for official Vue organization apps
Vue
1,329
star
38

vue-docs-zh-cn

č¯Ĩ饚į›Žåˇ˛ä¸å†įģ´æŠ¤īŧŒæœ‰åŠŗ通čŋ‡ Vue 厘įŊ‘æŸĨ阅最新įš„æ–‡æĄŖ
1,324
star
39

vueify

Browserify transform for single-file Vue components
JavaScript
1,168
star
40

vue-web-component-wrapper

(Vue 2 only) Wrap a Vue component as a web component / custom element.
JavaScript
1,047
star
41

test-utils

Vue Test Utils for Vue 3
TypeScript
1,038
star
42

docs-next-zh-cn

🇨đŸ‡ŗ Chinese translation for v3.vuejs.org
Vue
951
star
43

repl

Vue SFC REPL as a Vue 3 component
TypeScript
925
star
44

roadmap

đŸ—ēī¸ Roadmap for the Vue.js project (archive)
846
star
45

rollup-plugin-vue

Roll .vue files
TypeScript
843
star
46

vue-jest

Jest Vue transformer
JavaScript
748
star
47

vue-migration-helper

CLI tool to aid in migration from Vue 1.x to 2.0
JavaScript
594
star
48

vue-dev-server

A POC dev server that allows you to import `*.vue` files via native ES modules imports.
TypeScript
573
star
49

vue2-ssr-docs

Vue.js Server-Side Rendering Guide (for Vue 2)
563
star
50

vue-hot-reload-api

đŸŒļī¸ Hot reload API for Vue components
JavaScript
466
star
51

vue-animated-list

A Vue.js plugin for easily animating `v-for` rendered lists.
JavaScript
462
star
52

vue-eslint-parser

The ESLint custom parser for `.vue` files.
TypeScript
444
star
53

vue-next-webpack-preview

JavaScript
424
star
54

vue-async-data

Async data loading plugin
JavaScript
417
star
55

vue-component-compiler

Compile a single file Vue component into a CommonJS module.
TypeScript
343
star
56

vue-cli-plugin-vue-next

A Vue CLI plugin for trying out vue-next (experimental)
JavaScript
339
star
57

blog

📝 The official Vue.js blog
Vue
331
star
58

eslint-config-vue

JavaScript
327
star
59

component-compiler-utils

Lower level utilities for compiling Vue single file components
TypeScript
321
star
60

tsconfig

Base tsconfig for Vue 3 projects.
301
star
61

vue-test-utils-jest-example

Example project using Jest + vue-test-utils together
JavaScript
296
star
62

vue-template-explorer

Vue template compilation explorer
Vue
267
star
63

vue-codemod

Vue.js codemod scripts
TypeScript
261
star
64

events

Source code for the new Vue.js Events page
Vue
250
star
65

jp.vuejs.org

đŸ‡¯đŸ‡ĩ Japanese translation for vuejs.org
JavaScript
244
star
66

theme

VitePress theme for vuejs.org.
Vue
236
star
67

v3-migration-guide

Vue 2 -> Vue 3 migration guide
JavaScript
218
star
68

vue-element

register a custom element with Vue.js.
JavaScript
209
star
69

vue-curated

đŸ–ŧī¸ The curated Vue packages list
178
star
70

Discussion

Vue.js discussion
167
star
71

vuex-observable

Consume Vuex actions as Observables using RxJS 5
JavaScript
155
star
72

vue-issue-helper

Vue
145
star
73

composition-api-converter

Automatically migrate components to the Function API
JavaScript
145
star
74

art

🎨 Artworks
127
star
75

babel-preset-vue-app

Babel preset for Vue app.
JavaScript
124
star
76

eslint-config-typescript

eslint-config-typescript for vue projects
JavaScript
115
star
77

vue-router-demos

Live demos for vue-router
Vue
107
star
78

eslint-plugin-vue-libs

Eslint plugin for Vue internal development
JavaScript
106
star
79

laravel-elixir-vue-2

Laravel Elixir Vue 2.0 support plugin
JavaScript
105
star
80

vue-test-utils-mocha-webpack-example

Example project using mocha-webpack and vue-test-utils
JavaScript
104
star
81

composition-api-rfc

Vuepress render for the Composition API RFC
JavaScript
104
star
82

ecosystem-ci

Vue Ecosystem CI
TypeScript
92
star
83

babel-preset-vue

Babel preset for transforming Vue JSX.
JavaScript
88
star
84

vue-test-utils-getting-started

Demo project for `vue-test-utils`
JavaScript
81
star
85

vue-webpack-meteor-example

Example using Vue with Meteor, while leveraging the normal Webpack + NPM workflow for your front-end.
Vue
78
star
86

eslint-config-airbnb

ESLint Shareable Configs for Airbnb JavaScript Style Guide in Vue.js Projects
JavaScript
71
star
87

vue-requests

Need a Vue.js module or looking for ideas?
69
star
88

news.vuejs.org

Vue.js News Portal
Vue
67
star
89

vue-curated-client

Official curation list client
Vue
65
star
90

eslint-config-prettier

eslint-config-prettier for vue-cli
JavaScript
65
star
91

vue-test-utils-typescript-example

Example project using TypeScript, Jest + vue-test-utils together
Vue
61
star
92

vue-template-es2015-compiler

Support a subset of handy ES2015 features in Vue 2.0 templates.
JavaScript
61
star
93

create-vue-templates

Snapshots of the generated templates of `npm create vue@latest`
Vue
44
star
94

create-eslint-config

Utility to setup ESLint in Vue.js projects.
JavaScript
43
star
95

eslint-config-standard

ESLint Shareable Configs for JavaScript Standard Style in Vue.js Projects
JavaScript
40
star
96

vue-ssr-html-stream

Transform stream to simplify Vue SSR streaming
HTML
39
star
97

it.vuejs.org

Italian translation for vuejs.org 🇮🇹
JavaScript
35
star
98

systemjs-plugin-vue

SystemJS plugin for Vue single file components
JavaScript
34
star
99

test-utils-docs

Docs for vue-test-utils-next
JavaScript
33
star
100

vue-curated-server

JavaScript
31
star