Vue can do a lot of things. One of them, of course, is acting as the view layer for your apps. Actually, I think that’s the only intended purpose for Vue, but I know of a few others that are actually pretty neat. Today, we’ll eschew using Vue for the, well, view layer, and instead use it to… create a reactive data pipeline akin to RxJS Observables through the magic of computed properties. Yeah.
Now, there’s quite a bit of code here, and I’ll try to explain it as best I can, but it may be a bit difficult to understand.
The intended usage we’ll be aiming for will be something like this:
Now, whenever the original array changes, the callback for .subscribe will output the result of running that array through the pipeline. Slick, isn’t it? Oh, and did I mention that it works perfectly in Node too, without a browser environment?
All you need for this is Vue installed as a dependency. If you use normal require(), it runs under Node just fine.
The first step code-wise is to create a simple class with a few functions.
It’s pretty self-explanatory. Really all we’re doing is creating a bunch of functions that collect data and store it in the class for use by setupComponent()
.
Now, the tricky part is what happens in setupComponent
. Really, for what we’re trying to accomplish here it’s a bit overcomplicated (we could just use a single watcher and no computed properties,) but this method would allow you to add support for Vue’s dependency tracking system to cache computed properties and not rerun the whole thing when a dependency changes.
Once that’s done, you should be able to use it in the way demonstrated at the beginning of the article.
All together now:
The ReactivePipeline class…
… and usage:
BOOM! An RxJS-style Reactive data pipeline with Vue.js in less than 100 SLoC!
Just to rub it in, RxJS is ~140 kB minified, while Vue is around 60 kB. So you can have a view framework and your own custom observable system in less than half the size of RxJS. :D
I’m incredibly thankful for the work of Anirudh Sanjeev who first opened my eyes to the potential of Vue’s computed properties and set my imagination running like crazy with ideas.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!