setInterval() callback to control the clock hands by rotating them based on the current time.
Key Vue Concepts
The following Vue concepts are discussed in this article:
- Style binding with
- The HTML section fit inside the root
- The functions went into the
<style>section was moved into my Vue version unchanged
watchsections were not needed so they were removed
With those changes we can get pretty close to a working clock but not quite. The
querySelector() calls don’t have a place to go; without those, the rotation transforms aren’t going to work. To fix this I made just a couple of changes. First, I added three fields to the Vue Instance data object:
hourDegrees. These will hold the values in degrees for each clock hand.
Next, I changed the
setDate method to update those data fields. Note the usage of
this to reference the proper data fields within the Vue instance.
Then, I added a method
transformHandStyle that returns the transform style using degrees as its input.
And finally, I used Vue’s
:style binding to set the clock hands to the result of the
transformHandStyle method that is passed the corresponding data field.
Now let’s take a look at what the core of what the implementation looks like. I’ve annotated it to show how how it flows together.
- When the Vue instance is mounted, the
setDatemethod is called at intervals of 1 second (1000ms).
- Inside the
setDatefunction, the calculations for each hand is computed and set in the appropriate data field.
- Changes to the
hourDegreesdata fields activate Vue’s reactivity system to trigger calling the
transformHandStylemethod which sets the clock hand style.
transformHandStylemethod returns the css transform that rotates the clock hand.
Putting It All Together