Vue.js 3: Future-Oriented Programming

Vue.js 3: Future-Oriented Programming

How function-based API solves logic reusability problem

This article is aimed at people who have at least some background in JavaScript and Vue.
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.

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 mixinsoption) 🍹
  • 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 addscrollevent listener, track page offset and save it in pageOffsetproperty.

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, postsproperties initialized for loading state and posts data respectively. The fetchPosts method will be invoked after creating an instance and every time props.idchanges, 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 pageOffsetproperty 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 ue3.xto Vue2.xfor 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 setupfunction receives the resolved props object as its first argument and this propsobject is reactive. We also return an object containing pageOffsetproperty 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.

Top Vue.js Developers in USA

Top Vue.js Developers in USA

Vue.js is an extensively popular JavaScript framework with which you can create powerful as well as interactive interfaces. Vue.js is the best framework when it comes to building a single web and mobile apps.

We, at HireFullStackDeveloperIndia, implement the right strategic approach to offer a wide variety through customized Vue.js development services to suit your requirements at most competitive prices.

Vue.js is an open-source JavaScript framework that is incredibly progressive and adoptive and majorly used to build a breathtaking user interface. Vue.js is efficient to create advanced web page applications.

Vue.js gets its strength from the flexible JavaScript library to build an enthralling user interface. As the core of Vue.js is concentrated which provides a variety of interactive components for the web and gives real-time implementation. It gives freedom to developers by giving fluidity and eases the integration process with existing projects and other libraries that enables to structure of a highly customizable application.

Vue.js is a scalable framework with a robust in-build stack that can extend itself to operate apps of any proportion. Moreover, vue.js is the best framework to seamlessly create astonishing single-page applications.

Our Vue.js developers have gained tremendous expertise by delivering services to clients worldwide over multiple industries in the area of front-end development. Our adept developers are experts in Vue development and can provide the best value-added user interfaces and web apps.

We assure our clients to have a prime user interface that reaches end-users and target the audience with the exceptional user experience across a variety of devices and platforms. Our expert team of developers serves your business to move ahead on the path of success, where your enterprise can have an advantage over others.

Here are some key benefits that you can avail when you decide to hire vue.js developers in USA from HireFullStackDeveloperIndia:

  • A team of Vue.js developers of your choice
  • 100% guaranteed client satisfaction
  • Integrity and Transparency
  • Free no-obligation quote
  • Portal development solutions
  • Interactive Dashboards over a wide array of devices
  • Vue.js music and video streaming apps
  • Flexible engagement model
  • A free project manager with your team
  • 24*7 communication with your preferred means

If you are looking to hire React Native developers in USA, then choosing HireFullStackDeveloperIndia would be the best as we offer some of the best talents when it comes to Vue.js.