When are the props available in a component?
So, I came up with the following problem: In a component, I’m passing via props, an array of classes which I use on an inner element. These classes represent colouring the border and switching from one colour to the other every 1.5 seconds:
<MainContainer :colours="colours">
The obvious was to add the timer in the created method, something like this:
<template> ... <div :class="colour" class="main-container"> ... </template> <script> ... created() { // Set the first class as the initial one. this.colour = this.colours[tt % this.colours.length]; // Start the interval let tt = 0; setInterval(() => { tt++; this.color = this.colours[tt % this.colours.length]; }, 1500); }, ...
Unfortunately, this didn’t work. The interval did work, but not setting the initial value for the color property with the first element from the colours array. Why? Well, because during the “created” method, the props are not available yet! (the same goes for the “mounted” method)
So, what’s the solution? I created a computed property, with the following code:
computed: { theColour: function() { if (this.colour != '') { return this.colour } else if (this.colours.length > 0) { return this.colours[0]; } return "black" } },
In this one, I’ve introduced a new computed property called theColor, which combined the colour property, the colours array and a default “black” state in case there’s no colour defined yet.
Initially, since the colour variable is empty and the array colours is still empty, the if clause jumps directly to the “else case” (aka “black” colour) as the result. As soon as the props are populated, then the colours[0] will be returned. Through the interval, after 1.5 seconds, the colour will take the proper value and therefore control of the component.
Of course, I shouldn’t forget to adjust the div accordingly:
<MainContainer :colours="theColour">
And it worked. There is a small fraction of time where the class will be black, but it’s too small to cause any issue or complaint (therefore acceptable).
I’m sure that there are more solutions to this one. I’m looking forward to hearing about your solutions.