What is a Mixin in Vuejs ? Here's a simple explanation

profile picture

What is a Mixin in Vuejs ? Here's a simple explanation

TL;DR : A Mixin is a script file containing some logic that you can import into a vuejs component. It is structured exactly like in the script tag of a classic component. It's main objective is to prevent re-writing the same logic in multiple components.

For PHP folks out there, a mixin is basically like a Trait in php.

The official definitions states that a mixin is : "An array of option objects to be mixed into the current component."

The key word here is "mixed" into the component. Because when you import a mixin logic inside your component, you can still overwrite any of its methods, data, computed props, etc.

In a mixin, you can put anything you could put in the script section of a normal vue component.

Example:

One mixin I always use in all my vue project is the loading mixin:

// mixins/loading.js

export default {
    data () {
        return {
            isLoading: false,
        }
    },
    methods: {
        load () {
            this.isLoading = true
        },

        done () {
            this.isLoading = false
        },
    }
}

Vue Component :

<template>
    <div>
        <div v-if="isLoading">
            Loading...
        </div>
        <ul v-else>
            <li v-for="post in posts" :key="post.id">
                {{ post.title }}
            </li>
        </ul>
    </div>
</template>

<script>
import loading from './mixins/loading'
export default {
    mixins: [loading],

    data () {
        return {
            posts: []
        }
    },

    created () {
        this.getPosts()
    },

    methods: {
        getPosts () {
            this.load()
            axios.get('/api/posts')
                .then((response) => {
                    this.posts = response.data
                    this.done()
                })
        }
    }
}
</script>

You can of override the methods, data, props, etc in the component itself

vuejs
vue
mixin

about me

profile picture

I consider myself as an IT Business Artisan. Or Consultant CTO. I'm a self-taught Web Developper, coach and teacher. My main work is helping and guiding digital startups.

more about me

follow me

newsletter

A weekly email with the latests articles

support my work

Start trading on binance
  • BTC

    BTC

    18SY81ejLGFuJ9KMWQu5zPrDGuR5rDiauM

  • ETH

    ETH

    0x519e0eaa9bc83018bb306880548b79fc0794cd08

  • Monero

    XMR

    895bSneY4eoZjsr2hN2CAALkUrMExHEV5Pbg8TJb6ejnMLN7js1gLAXQySqbSbfzjWHQpQhQpvFtojbkdZQZmM9qCFz7BXU

2024 © My Dynamic Production SRL All rights Reserved.