Vue.js 3: Future-Oriented Programming

How function-based API solves logic reusability problem

If you are interested in Vue.js, you probably know about the 3rd version of this framework, which will be released shortly (if you are reading this article from the future, I hope it’s still relevant 😉). The new version is under active development for now, but all possible features can be found in separate RFC (request for comments) repository: https://github.com/vuejs/rfcs. One of them, function-api, can dramatically change the style of developing Vue apps.

This article is aimed at people who have at least some background in JavaScript and Vue.

Before we start: Use Bit to encapsulate Vue components with all their dependencies and setup. Build truly modular applications with better code reuse, simpler maintenance and less overhead. Share and collaborate on individual Vue components.

Components with Bit: Easily share across projects as a team

What’s wrong with the current API? 👀

The best way is to show everything in an example. So, let’s imagine that we need to implement a component that should fetch some user’s data, show loading state and topbar depending on scroll offset. Here is the final result:

Live example you can check here.

It is good practice to extract some logic to reuse across multiple components. With Vue 2.x’s current API, there are a number of common patterns, most well known are:

Mixins (via the mixins option) 🍹

option) 🍹 Higher-order components (HOCs) 🎢

So, let’s move scroll tracking logic into a mixin, and fetching logic into a higher-order component. Typical implementation with Vue you can see below.

Scroll mixin:

Here we add scroll event listener, track page offset and save it in pageOffset property.

The higher-order component will look like this:

Here isLoading , posts properties initialized for loading state and posts data respectively. The fetchPosts method will be invoked after creating an instance and every time props.id changes, in order to fetch data for new id .

It’s not a complete implementation of HOC, but for this example, it will be enough. Here we just wrap the target component and pass original props alongside fetch-related props.

Target component looks like this:

To get specified props it should be wrapped in created HOC:

const PostsPage = withPostsHOC(PostsPage)

Full component with template and styles can be found here.

Great! 🥳 We just implemented our task using mixin and HOC, so they can be used by other components. But not everything is so rosy, there are several problems with these approaches.

1. Namespace clashing ⚔️

Imagine that we need to add update method to our component:

If you open the page again and scroll it, the topbar will not be shown anymore. This is due to the overwriting of mixin’s method update . The same works for HOCs. If you change the data field fetchedPosts to posts :

…you will get errors like this:

The reason for this is that wrapped component already specified property with the name posts .

2. Unclear sources 📦

What if after some time you decided to use another mixin in your component:

Can you tell exactly which mixin a pageOffset property was injected from? Or in another scenario, both mixins can have, for example, yOffset property, so the last mixin will override property from the previous one. That’s not good and can cause a lot of unexpected bugs. 😕

3. Performance ⏱

Another problem with HOCs is that we need separate component instances created just for logic reuse purposes that come at a performance cost.

Let’s “setup” 🏗

Let’s see what alternative can offer the next Vue.js release and how we can solve the same problem using function-based API.

Since Vue 3 is not released yet, the helper plugin was created — vue-function-api. It provides function api from Vue3.x to Vue2.x for developing next-generation Vue applications.

Firstly, you need to install it:

$ npm install vue-function-api

and explicitly install via Vue.use() :

import Vue from 'vue'

import { plugin } from 'vue-function-api'



Vue.use(plugin)

The main addition function-based API provides is a new component option - setup() . As the name suggests, this is the place where we use the new API’s functions to setup the logic of our component. So, let’s implement a feature to show topbar depending on scroll offset. Basic component example:

Note that the setup function receives the resolved props object as its first argument and this props object is reactive. We also return an object containing pageOffset property to be exposed to the template’s render context. This property becomes reactive too, but on the render context only. We can use it in the template as usual:

<div class="topbar" :class="{ open: pageOffset > 120 }">...</div>

But this property should be mutated on every scroll event. To implement this, we need to add scroll event listener when the component will be mounted and remove the listener — when unmounted. For these purposes value , onMounted , onUnmounted API functions exist:

Note that all lifecycle hooks in 2.x version of Vue have an equivalent onXXX function that can be used inside setup() .

You probably also noticed that pageOffset variable contains a single reactive property: .value . We need to use this wrapped property because primitive values in JavaScript like numbers and strings are not passed by reference. Value wrappers provide a way to pass around mutable and reactive references for arbitrary value types.

Here’s how the pageOffset object looks like:

The next step is to implement the user’s data fetching. As well as when using option-based API, you can declare computed values and watchers using function-based API:

A computed value behaves just like a 2.x computed property: it tracks its dependencies and only re-evaluates when dependencies have changed. The first argument passed to watch is called a "source", which can be one of the following:

a getter function

a value wrapper

an array containing the two above types

The second argument is a callback that will only get called when the value returned from the getter or the value wrapper has changed.

We just implemented the target component using function-based API. 🎉 The next step is to make all this logic reusable.

Decomposition 🎻 ✂️

This is the most interesting part, to reuse code related to a piece of logic we just can extract it into what called a “composition function” and return reactive state:

Note how we used useFetchPosts and useScroll functions to return reactive properties. These functions can be stored in separate files and used in any other component. Compared to the option-based solution:

Properties exposed to the template have clear sources since they are values returned from composition functions;

Returned values from composition functions arbitrarily named so there is no namespace collision;

There are no unnecessary component instances created just for logic reuse purposes.

There are a lot of other benefits that can be found on the official RFC page.

All code examples used in this article you can find here.

Live example of the component you can check here.

Conclusion

As you can see Vue’s function-based API presents a clean and flexible way to compose logic inside and between components without any of option-based API drawbacks. Just imagine how powerful composition functions could be for any type of project — from small to big, complex web apps. 🚀

I hope this post was useful 🎓. If you have any thoughts or questions, please feel free to respond and comment below! I will be glad to answer 🙂. Thanks.

Related Stories