mercredi 3 juin 2020

Set random global color from array with Nuxt on page load

In a Nuxt app, I want to set a global random color from an array on page load. It should remain the same while browsing the page and only change on hard page reload.

I am a Vue/Nuxt beginner but have so far understood that I probably should set this up with a Vuex store. The color only needs to be set/mutated once (when the website is first loaded). But I am stuck with figuring out the right code, and the right place to first set the variable (on the landing page? In the layout page used for the landing page? In the Vuex store? ...).

I have so far come up with a mixin that picks a random number:

// globalColor.js 

export default {
    data() {
        return {
            list: ['red', 'green', 'yellow', 'blue', 'pink', 'orange'],
            globalColor: ''
        }
    },
    created() {
        const randomColor = Math.floor(Math.random() * this.list.length)
        this.globalColor = this.list[randomColor]
    }
}

Any pointers on how to turn globalColor into a global state and where best to run this? Thanks a lot in advance!




Aucun commentaire:

Enregistrer un commentaire