Transferring from Vanilla JavaScript to a Reusable Vue Element

I not too long ago wrote an article explaining how one can create a countdown timer utilizing HTML, CSS and JavaScript. Now, let’s take a look at how we are able to make reusable element by porting it into Vue utilizing primary options that the framework gives.

Why do that in any respect? Nicely there are few causes, however two stand out particularly:

Maintaining UI in sync with the timer state: When you take a look at the code from the primary put up,  all of it lives within the timerInterval perform, most noticeably the state administration. Every time it runs (each second) we have to manually discover the right aspect on our doc — whether or not it’s the time label or the remaining time path or no matter — and alter both its worth or an attribute. Vue comes with an HTML-based template syntax that permits you to declaratively bind the rendered DOM to the underlying Vue occasion’s information. That takes all of the burden of discovering and updating correct UI components so we are able to rely purely on the element occasion’s properties.Having a extremely reusable element: The authentic instance works wonderful when just one timer is current on our doc, however think about that you just need to add one other one. Oops! We rely the aspect’s ID to carry out our actions and utilizing the identical ID on a number of cases would forestall them from working independently. Which means we must assign completely different IDs for every timer. If we create a Vue element, all it’s logic is encapsulated and related to that particular occasion of the element. We will simply create 10, 20, 1,000 timers on a single doc with out altering a single line within the element itself!

Right here’s the identical timer we created collectively within the final put up, however in Vue.

Template and kinds

From the Vue docs:

Vue makes use of an HTML-based template syntax that permits you to declaratively bind the rendered DOM to the underlying Vue occasion’s information. All Vue.js templates are legitimate HTML that may be parsed by spec-compliant browsers and HTML parsers.

Let’s create our element by opening a brand new file referred to as BaseTimer.vue. Right here’s the fundamental construction we want for that:

// Our template markup will go right here

// Our purposeful scripts will go right here

// Our styling will go right here

On this step, we’ll focus on the