In VueJS there are few ways to compose components and reuse logic. In this article, I would like to demonstrate a way to boost composition in Vuejs (2.* and 3.*).

I really like the recent proposals regarding the Composition API, but I think that can be part of a broader view.

Below, you can find a component implementing a general use case (a simple data fetching from a remote endpoint and displaying the different transitions and data), though most of the logic is always duplicated along with the template, data, and other variables when the same logic is applied to other places or components.

<template>
<div>
    <div v-if="loading"> Loading... </div>
    <div v-if="error"> An Error occured, please try again</div>
    <div v-if="hasData"> {{ data }} </div>
</div>
</template>

</template>

<script>
    export default {
        data() {
            return {
                loading: false,
                error: false,
                data: {}
            }
        },
        methods: {
            fetchData() {
                this.loading = true;
                setTimeout(() => {
                    this.data = { text: 'example' };
                    this.loading = false;
                }, 4000);
            }
        },
        computed: {
            hasData() {
                return this.data && !!this.data.text;
            }
        },
        mounted() {
            this.fetchData();
        }
    }
</script>

How do we refactor this component and improve it? Let’s go step-by-step and make this component more readable and reusable.

#functional #components #vuejs #jsx #composition #vue

Better Component Composition in VueJS
1.90 GEEK