Vue.js 3 is Future-Oriented Programming, Don't miss !

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.

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:

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)
  • 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:

const scrollMixin = {
    data() {
        return {
            pageOffset: 0
        }
    },
    mounted() {
        window.addEventListener('scroll', this.update)
    },
    destroyed() {
        window.removeEventListener('scroll', this.update)
    },
    methods: {
        update() {
            this.pageOffset = window.pageYOffset
        }
    }
}

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

The higher-order component will look like this:

import { fetchUserPosts } from '@/api'

const withPostsHOC = WrappedComponent => ({
    props: WrappedComponent.props,
    data() {
        return {
            postsIsLoading: false,
            fetchedPosts: []
        }
    },
    watch: {
        id: {
            handler: 'fetchPosts',
            immediate: true
        }
    },
    methods: {
        async fetchPosts() {
            this.postsIsLoading = true
            this.fetchedPosts = await fetchUserPosts(this.id)
            this.postsIsLoading = false
        }
    },
    computed: {
        postsCount() {
            return this.fetchedPosts.length
        }
    },
    render(h) {
        return h(WrappedComponent, {
            props: {
                ...this.$props,
                isLoading: this.postsIsLoading,
                posts: this.fetchedPosts,
                count: this.postsCount
            }
        })
    }
})

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:

// ...
<script>
export default {
    name: 'PostsPage',
    mixins: [scrollMixin],
    props: {
        id: Number,
        isLoading: Boolean,
        posts: Array,
        count: Number
    }
}
</script>
// ...

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:

// ...
<script>
export default {
    name: 'PostsPage',
    mixins: [scrollMixin],
    props: {
        id: Number,
        isLoading: Boolean,
        posts: Array,
        count: Number
    },
    methods: {
        update() {
            console.log('some update logic here')
        }
    }
}
</script>
// ...

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:

const withPostsHOC = WrappedComponent => ({
    props: WrappedComponent.props, // ['posts', ...]
    data() {
        return {
            postsIsLoading: false,
            posts: [] // fetchedPosts -> 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:

// ...
<script>
export default {
    name: 'PostsPage',
    mixins: [scrollMixin, mouseMixin],
// ...

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:

// ...
<script>
export default {
  setup(props) {
    const pageOffset = 0
    return {
      pageOffset
    }
  }
}
</script>
// ...

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:

// ...
<script>
import { value, onMounted, onUnmounted } from 'vue-function-api'
export default {
  setup(props) {
    const pageOffset = value(0)
    const update = () => {
        pageOffset.value = window.pageYOffset
    }
    
    onMounted(() => window.addEventListener('scroll', update))
    onUnmounted(() => window.removeEventListener('scroll', update))
    
    return {
      pageOffset
    }
  }
}
</script>
// ...

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:

// ...
<script>
import {
    value,
    watch,
    computed,
    onMounted,
    onUnmounted
} from 'vue-function-api'
import { fetchUserPosts } from '@/api'
export default {
  setup(props) {
    const pageOffset = value(0)
    const isLoading = value(false)
    const posts = value([])
    const count = computed(() => posts.value.length)
    const update = () => {
      pageOffset.value = window.pageYOffset
    }
    
    onMounted(() => window.addEventListener('scroll', update))
    onUnmounted(() => window.removeEventListener('scroll', update))
    
    watch(
      () => props.id,
      async id => {
        isLoading.value = true
        posts.value = await fetchUserPosts(id)
        isLoading.value = false
      }
    )
    
    return {
      isLoading,
      pageOffset,
      posts,
      count
    }
  }
}
</script>
// ...

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:

// ...
<script>
import {
    value,
    watch,
    computed,
    onMounted,
    onUnmounted
} from 'vue-function-api'
import { fetchUserPosts } from '@/api'
function useScroll() {
    const pageOffset = value(0)
    const update = () => {
        pageOffset.value = window.pageYOffset
    }
    onMounted(() => window.addEventListener('scroll', update))
    onUnmounted(() => window.removeEventListener('scroll', update))
    return { pageOffset }
}
function useFetchPosts(props) {
    const isLoading = value(false)
    const posts = value([])
    watch(
        () => props.id,
        async id => {
            isLoading.value = true
            posts.value = await fetchUserPosts(id)
            isLoading.value = false
        }
    )
    return { isLoading, posts }
}
export default {
    props: {
        id: Number
    },
    setup(props) {
        const { isLoading, posts } = useFetchPosts(props)
        const count = computed(() => posts.value.length)
        return {
            ...useScroll(),
            isLoading,
            posts,
            count
        }
    }
}
</script>
// ...

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.

#javascript #vue.js #programming #Front End Development #wevdev

Vue.js 3 is Future-Oriented Programming, Don't miss !
2 Likes71.90 GEEK