Skip to content

Introduction to VueJS and RxJS

This article was written over 18 months ago and may contain information that is out of date. Some content may be relevant but please refer to the relevant official documentation or available resources for the latest information.

Let's start with a brief introduction.

What is VueJS

Vue.js is a progressive open-source front end JavaScript framework for building user interfaces, and single-page applications.

What is RxJS

RxJS is a library for reactive programming, and has components that enable the composition of asynchronous code. This means it takes data as streams (Observables) that can be subscribe to.

Installation/Setup

Following these steps, let's set-up our Vue application, and install RxJS:

Vue create <AppName>

yarn i rxjs

yarn serve

Creating an Observable

To create an observable

  new Observable(function subscribe(subscriber) {});

An observer of an observable is an object with three functions: next, error, & complete.

observable.subscribe({
  next: value => console.log(value),
  error: err => console.log(err),
  complete: () => console.log(`Completed`),
})

Let's take a look at an example to better understand Observables.

<script lang="ts">
import { defineComponent, onMounted, onBeforeUnmount } from "vue";
import { Observable, Subscription} from "rxjs";

export default defineComponent({
  setup() {
    const time = 2500;
    let observableID: Subscription
    onMounted(() => {
      const observable$ = new Observable(function subscribe(subscriber) {
        const intervalId = setInterval(() => {
          subscriber.next("Vuejs and Rxjs");
          subscriber.complete();
          clearInterval(intervalId);
        }, time);
      });
      observableID = observable$.subscribe(
        (value) => console.log(`Introduction to ${value}`),
        (err) => console.log(err),
        () => console.log("completed")
      );
    });
    onBeforeUnmount(() => observableID.unsubscribe()); 
  },
});
</script>

From the example above, we can see that “Introduction to Vuejs and Rxjs” is printed out after 2.5 seconds, and then "completed" is printed after.

RxjS operators

Creating an observable manually every time can make code become very lengthy and difficult to read. Therefore, RxJS has alot of useful operators.

Some of the most commonly used operators are

  • Creation Operators
  • Transformation Operators
  • Filtering Operators
  • Combination Operators
  • Conditional Operators
  • Join Operators
  • Multicasting Operators
  • Error Handling Operators

We would be discussing examples on Creation, Transformation, and Filtering operators in this post:

Creation operators

These operators make creating an observable easy for various usecase. Some examples are 'interval', 'from', and 'of'.

  • interval: Creates an observable that emits sequential numbers every specified interval of time.
  interval(10).subscribe(console.log);
  • from: Creates an observable from an array, promise, iterables or string
const frameworks = of("VueJS", "ReactJS", "Svelte", "AngularJS", "Lit", "RiotJS").subscribe(val => console.log(val));

//output: "VueJS", "ReactJS", "Svelte", "AngularJS",  "Lit", "RiotJS",

const promiseSource = from(new Promise(resolve => resolve('Hello World!'))).subscribe(val => console.log(val));

//output: 'Hello World!'
  • of: Creates an observable from a sequence of values
const frameworks = of("VueJS", "ReactJS", "Svelte", "AngularJS", "Lit", "RiotJS").subscribe(val => console.log(val));

//output: "VueJS", "ReactJS", "Sevelte", "AngularJS",  "Lit", "RiotJS"

Transformation operators

These operators provide data transformation techniques for values passing through.

An example is 'map'. For the example below, we use map to transform our array of objects ([{name: "VueJS", language: "js"}]) into an array of strings(["VueJS"]).

    const source = [
      { name: "VueJS", language: "js" },
      { name: "ReactJS", language: "js" },
      { name: "Laravel", language: "PHP" },
      { name: "Sevelte", language: "js" },
      { name: "AngularJS", language: "js" },
      { name: "Spring", language: "java" },
      { name: "Lit", language: "js" },
      { name: "CodeIgniter", language: "PHP" },
      { name: "RiotJS", language: "js" },
    ];

    from(source).pipe(map(({ name }) => name));
    jsFrameworks.subscribe((value) => {
      frameworks.value.push(value);
    });

Filtering Operator

This operator helps in choosing and refining how and when data is obtained from an observable.

An example is "Filter". For the example below, we use "filter" to obtain an array of objects where language is "js".

    const source = [
      { name: "VueJS", language: "js" },
      { name: "ReactJS", language: "js" },
      { name: "Laravel", language: "PHP" },
      { name: "Svelte", language: "js" },
      { name: "AngularJS", language: "js" },
      { name: "Spring", language: "java" },
      { name: "Lit", language: "js" },
      { name: "CodeIgniter", language: "PHP" },
      { name: "RiotJS", language: "js" },
    ];
    from(source).pipe(
      filter(({ language }) => language === "js"),
      map(({ name }) => name)
    );

Example

Now that we have discussed some of the basics, lets try building a page that shows a list of frameworks. Each item of the list should be delayed before being displayed.

<template>
  <div>
    Test Rxjs
    <h2>Filter Frameworks</h2>
    <ul>
      <li v-for="item in frameworks" :key="item">{{ item }}</li>
    </ul>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from "vue";
import { interval } from "rxjs";
import { map, filter } from "rxjs/operators";

export default defineComponent({
  setup() {
    let frameworks = ref([]);
    const time = 1000;

    const source = [
      { name: "VueJS", language: "js" },
      { name: "ReactJS", language: "js" },
      { name: "Laravel", language: "PHP" },
      { name: "Svelte", language: "js" },
      { name: "AngularJS", language: "js" },
      { name: "Spring", language: "java" },
      { name: "Lit", language: "js" },
      { name: "CodeIgniter", language: "PHP" },
      { name: "RiotJS", language: "js" },
    ];

    onMounted(() => {
      const jsFrameworks = interval(time).pipe(
        filter((i) => source[i].language === "js"),
        map((i) => source[i].name)
      );
      const observable$ = jsFrameworks.subscribe(
        (value) => {
          frameworks.value.push(value);
        },
        () => observable$.unsubscribe()
      );
    });
    return {
      frameworks,
    };
  },
});
</script>

Live Demo

This is a codesandbox demo for you to play around with:

Conclusion

RxJS is really expansive, and can't be covered in just a single blog post. To learn more about RxJs, checkout the official documentation here: https://rxjs.dev/ or https://www.learnrxjs.io/. There is also a very good Vue plugin for Rxjs here.

If you have any questions or run into any trouble, feel free to reach out on Twitter or Github.

This Dot is a consultancy dedicated to guiding companies through their modernization and digital transformation journeys. Specializing in replatforming, modernizing, and launching new initiatives, we stand out by taking true ownership of your engineering projects.

We love helping teams with projects that have missed their deadlines or helping keep your strategic digital initiatives on course. Check out our case studies and our clients that trust us with their engineering.

You might also like

3 VueJS Component Libraries Perfect for Beginners cover image

3 VueJS Component Libraries Perfect for Beginners

For developers checking out VueJS for the first time, the initial steps are overwhelming, particularly when setting up projects from square one. But don’t worry! The VueJS ecosystem offers a plethora of remarkable component libraries, easing this early obstacle. These three libraries are pre-built toolkits, providing beginners with the means to kickstart their VueJS projects effortlessly. Let’s take a look! Quasar Quasar is among the most popular open-source component libraries for Vue.js, offering a comprehensive set of ready-to-use UI components and tools for building responsive web applications and websites. Designed with performance, flexibility, and ease of use in mind, Quasar provides developers with a wide range of customizable components, such as buttons, forms, dialogs, and layouts, along with built-in support for themes, internationalization, and accessibility. With its extensive documentation, active community support, and seamless integration with Vue CLI and Vuex, Quasar empowers developers to rapidly prototype and develop high-quality Vue.js applications for various platforms, including desktop, mobile, and PWA (Progressive Web Apps). PrimeVue PrimeVue is a popular Vue.js component library offering a wide range of customizable UI components designed for modern web applications. Developed by PrimeTek, it follows Material Design guidelines, ensuring responsiveness and accessibility across devices. With features like theming, internationalization, and advanced functionalities such as lazy loading and drag-and-drop, PrimeVue provides developers with the tools to create elegant and high-performing Vue.js applications efficiently. Supported by clear documentation, demos, and an active community, PrimeVue is an excellent choice for developers seeking to streamline their development process and deliver polished user experiences. Vuetify Vuetify is a powerful Vue.js component library that empowers developers to create elegant and responsive user interfaces with ease. Built according to Google's Material Design guidelines, Vuetify offers a vast collection of customizable UI components, ranging from buttons and cards to navigation bars and data tables. Its comprehensive set of features includes themes, typography, layout grids, and advanced components like dialogues and sliders, enabling developers to quickly build modern web applications that look and feel polished. With extensive documentation, active community support, and ongoing development, Vuetify remains a top choice for Vue.js developers seeking to streamline their workflow and deliver visually stunning user experiences. For newcomers venturing into Vue.js, the initial setup might seem daunting. Thankfully, Vue.js offers a variety of component libraries to simplify this process. Quasar, PrimeVue, and Vuetify are standout options, each providing pre-built tools to kickstart projects smoothly. Whether you prefer Quasar's extensive UI components, PrimeVue's Material Design-inspired features, or Vuetify's responsive interfaces, these libraries cater to diverse preferences and project requirements. With their clear documentation and active communities, these libraries empower developers to start Vue.js projects confidently and efficiently, enabling Vue developers to create polished user experiences....

Nuxt DevTools v1.0: Redefining the Developer Experience Beyond Conventional Tools cover image

Nuxt DevTools v1.0: Redefining the Developer Experience Beyond Conventional Tools

In the ever-evolving world of web development, Nuxt.js has taken a monumental leap with the launch of Nuxt DevTools v1.0. More than just a set of tools, it's a game-changer—a faithful companion for developers. This groundbreaking release, available for all Nuxt projects and being defaulted from Nuxt v3.8 onwards, marks the beginning of a new era in developer tools. It's designed to simplify our development journey, offering unparalleled transparency, performance, and ease of use. Join me as we explore how Nuxt DevTools v1.0 is set to revolutionize our workflow, making development faster and more efficient than ever. What makes Nuxt DevTools so unique? Alright, let's start delving into the features that make this tool so amazing and unique. There are a lot, so buckle up! In-App DevTools The first thing that caught my attention is that breaking away from traditional browser extensions, Nuxt DevTools v1.0 is seamlessly integrated within your Nuxt app. This ensures universal compatibility across browsers and devices, offering a more stable and consistent development experience. This setup also means the tools are readily available in the app, making your work more efficient. It's a smart move from the usual browser extensions, making it a notable highlight. To use it you just need to press Shift + Option + D (macOS) or Shift + Alt + D (Windows): With simple keystrokes, the Nuxt DevTools v1.0 springs to life directly within your app, ready for action. This integration eliminates the need to toggle between windows or panels, keeping your workflow streamlined and focused. The tools are not only easily accessible but also intelligently designed to enhance your productivity. Pages, Components, and Componsables View The Pages, Components, and Composables View in Nuxt DevTools v1.0 are a clear roadmap for your app. They help you understand how your app is built by simply showing its structure. It's like having a map that makes sense of your app's layout, making the complex parts of your code easier to understand. This is really helpful for new developers learning about the app and experienced developers working on big projects. Pages View lists all your app's pages, making it easier to move around and see how your site is structured. What's impressive is the live update capability. As you explore the DevTools, you can see the changes happening in real-time, giving you instant feedback on your app's behavior. Components View is like a detailed map of all the parts (components) your app uses, showing you how they connect and depend on each other. This helps you keep everything organized, especially in big projects. You can inspect components, change layouts, see their references, and filter them. By showcasing all the auto-imported composables, Nuxt DevTools provides a clear overview of the composables in use, including their source files. This feature brings much-needed clarity to managing composables within large projects. You can also see short descriptions and documentation links in some of them. Together, these features give you a clear picture of your app's layout and workings, simplifying navigation and management. Modules and Static Assets Management This aspect of the DevTools revolutionizes module management. It displays all registered modules, documentation, and repository links, making it easy to discover and install new modules from the community! This makes managing and expanding your app's capabilities more straightforward than ever. On the other hand, handling static assets like images and videos becomes a breeze. The tool allows you to preview and integrate these assets effortlessly within the DevTools environment. These features significantly enhance the ease and efficiency of managing your app's dynamic and static elements. The Runtime Config and Payload Editor The Runtime Config and Payload Editor in Nuxt DevTools make working with your app's settings and data straightforward. The Runtime Config lets you play with different configuration settings in real time, like adjusting settings on the fly and seeing the effects immediately. This is great for fine-tuning your app without guesswork. The Payload Editor is all about managing the data your app handles, especially data passed from server to client. It's like having a direct view and control over the data your app uses and displays. This tool is handy for seeing how changes in data impact your app, making it easier to understand and debug data-related issues. Open Graph Preview The Open Graph Preview in Nuxt DevTools is a feature I find incredibly handy and a real time-saver. It lets you see how your app will appear when shared on social media platforms. This tool is crucial for SEO and social media presence, as it previews the Open Graph tags (like images and descriptions) used when your app is shared. No more deploying first to check if everything looks right – you can now tweak and get instant feedback within the DevTools. This feature not only streamlines the process of optimizing for social media but also ensures your app makes the best possible first impression online. Timeline The Timeline feature in Nuxt DevTools is another standout tool. It lets you track when and how each part of your app (like composables) is called. This is different from typical performance tools because it focuses on the high-level aspects of your app, like navigation events and composable calls, giving you a more practical view of your app's operation. It's particularly useful for understanding the sequence and impact of events and actions in your app, making it easier to spot issues and optimize performance. This timeline view brings a new level of clarity to monitoring your app's behavior in real-time. Production Build Analyzer The Production Build Analyzer feature in Nuxt DevTools v1.0 is like a health check for your app. It looks at your app's final build and shows you how to make it better and faster. Think of it as a doctor for your app, pointing out areas that need improvement and helping you optimize performance. API Playground The API Playground in Nuxt DevTools v1.0 is like a sandbox where you can play and experiment with your app's APIs. It's a space where you can easily test and try out different things without affecting your main app. This makes it a great tool for trying out new ideas or checking how changes might work. Some other cool features Another amazing aspect of Nuxt DevTools is the embedded full-featured VS Code. It's like having your favorite code editor inside the DevTools, with all its powerful features and extensions. It's incredibly convenient for making quick edits or tweaks to your code. Then there's the Component Inspector. Think of it as your code's detective tool. It lets you easily pinpoint and understand which parts of your code are behind specific elements on your page. This makes identifying and editing components a breeze. And remember customization! Nuxt DevTools lets you tweak its UI to suit your style. This means you can set up the tools just how you like them, making your development environment more comfortable and tailored to your preferences. Conclusion In summary, Nuxt DevTools v1.0 marks a revolutionary step in web development, offering a comprehensive suite of features that elevate the entire development process. Features like live updates, easy navigation, and a user-friendly interface enrich the development experience. Each tool within Nuxt DevTools v1.0 is thoughtfully designed to simplify and enhance how developers build and manage their applications. In essence, Nuxt DevTools v1.0 is more than just a toolkit; it's a transformative companion for developers seeking to build high-quality web applications more efficiently and effectively. It represents the future of web development tools, setting new standards in developer experience and productivity....

Testing Vue Composables with Jest cover image

Testing Vue Composables with Jest

In this post, we will take a look at how to test Vue composables with Jest. What Are Composables? When developing large scale frontend applications, we reuse logic for repetitive tasks. With composables, we are able to resuse logic in a stateful manner with the help of the composition API. Testing For this example, we create a composable to handle changes in screen size. Depending on how complex your composable is, you can simply test the reactivity directly or load it into a wrapper component, and then test the wrapper component. ` Let's write the following tests for this composable. - check currect value of screen size - check currect value of screen size after resize event is fired To test that the resize event changes the current value when fired, we need to load our composable in a component. ` From the implementation we completed above, the core logic of our breakpoint method is in an external function called "composable", and we can simply reuse it across our frontend code. Any manipulation to the state of a composable should be done directly within the composable to avoid bugs and make it easier to read. I hope this article has been helpful. If you have any questions or run into any trouble, feel free to reach out on Twitter or Github....

The simplicity of deploying an MCP server on Vercel cover image

The simplicity of deploying an MCP server on Vercel

The current Model Context Protocol (MCP) spec is shifting developers toward lightweight, stateless servers that serve as tool providers for LLM agents. These MCP servers communicate over HTTP, with OAuth handled clientside. Vercel’s infrastructure makes it easy to iterate quickly and ship agentic AI tools without overhead. Example of Lightweight MCP Server Design At This Dot Labs, we built an MCP server that leverages the DocuSign Navigator API. The tools, like `get_agreements`, make a request to the DocuSign API to fetch data and then respond in an LLM-friendly way. ` Before the MCP can request anything, it needs to guide the client on how to kick off OAuth. This involves providing some MCP spec metadata API endpoints that include necessary information about where to obtain authorization tokens and what resources it can access. By understanding these details, the client can seamlessly initiate the OAuth process, ensuring secure and efficient data access. The Oauth flow begins when the user's LLM client makes a request without a valid auth token. In this case they’ll get a 401 response from our server with a WWW-Authenticate header, and then the client will leverage the metadata we exposed to discover the authorization server. Next, the OAuth flow kicks off directly with Docusign as directed by the metadata. Once the client has the token, it passes it in the Authorization header for tool requests to the API. ` This minimal set of API routes enables me to fetch Docusign Navigator data using natural language in my agent chat interface. Deployment Options I deployed this MCP server two different ways: as a Fastify backend and then by Vercel functions. Seeing how simple my Fastify MCP server was, and not really having a plan for deployment yet, I was eager to rewrite it for Vercel. The case for Vercel: * My own familiarity with Next.js API deployment * Fit for architecture * The extremely simple deployment process * Deploy previews (the eternal Vercel customer conversion feature, IMO) Previews of unfamiliar territory Did you know that the MCP spec doesn’t “just work” for use as ChatGPT tooling? Neither did I, and I had to experiment to prove out requirements that I was unfamiliar with. Part of moving fast for me was just deploying Vercel previews right out of the CLI so I could test my API as a Connector in ChatGPT. This was a great workflow for me, and invaluable for the team in code review. Stuff I’m Not Worried About Vercel’s mcp-handler package made setup effortless by abstracting away some of the complexity of implementing the MCP server. It gives you a drop-in way to define tools, setup https-streaming, and handle Oauth. By building on Vercel’s ecosystem, I can focus entirely on shipping my product without worrying about deployment, scaling, or server management. Everything just works. ` A Brief Case for MCP on Next.js Building an API without Next.js on Vercel is straightforward. Though, I’d be happy deploying this as a Next.js app, with the frontend features serving as the documentation, or the tools being a part of your website's agentic capabilities. Overall, this lowers the barrier to building any MCP you want for yourself, and I think that’s cool. Conclusion I'll avoid quoting Vercel documentation in this post. AI tooling is a critical component of this natural language UI, and we just want to ship. I declare Vercel is excellent for stateless MCP servers served over http....

Let's innovate together!

We're ready to be your trusted technical partners in your digital innovation journey.

Whether it's modernization or custom software solutions, our team of experts can guide you through best practices and how to build scalable, performant software that lasts.

Prefer email? hi@thisdot.co