Creating customized, repeatable HTML elements cuts down on the amount of code you have to write. It also adds organization and readability to your codebase. So how does one create custom HTML elements? Vue.JS provides an elegant solution.
Including Vue in your project is as easy as copying and pasting the following script: <script src=”https://unpkg.com/vue/dist/vue.js”></script>. Do note that you’ll want to include the tag (and reference to your own .js file of course) between the closing </body> and </html> tags. Putting the tags there will allow for the body to load up before calling the scripts. Your full document might look something like this:
Next, you’ll want to add an HTML element for Vue.JS to target; simply add a div element with id=”vue”. Like this:
Now we’ll use Vue’s component method to create our custom HTML. Note: You’ll want to call the component method BEFORE the new Vue instance. 2 Arguments are passed 1) the name of the custom element, and 2) an object containing a template with the HTML.
With the HTML, you’ll want to start with a single top-level element that contains everything else. It makes sense to use a div, and it also makes sense to give that div an id (or class name) that matches the name of the custom element. Doing so allows for easy CSS targeting. Lastly, it’s advisable to use template literal syntax for clean formatting. All together, it will look something like this:
Now for the good stuff; let’s get that custom HTML going! For my example here, I’m going to go with a simple custom banner element. I’ve got it all coded up in a CodePen and it looks like this:
You can write in whatever valid html you want. The final step is to put the custom element tags (i.e., the name you passed to the component method) in the target element HTML (e.g., <div id=”vue”></div>). Make sure to click on the HTML tab in the preview above to see what that looks like. Notice that you only need to use the custom element tags 1 time in order to render all of the HTML.
So there you have it. With Vue.JS, creating customized reusable HTML is a snap. As always, thank you for reading… Stay tuned for more!