There are a few common UI components that I often use in my VueJS projects, especially when bringing in a framework like Bootstrap. One component that I find myself using a lot is a simple button component. Using Bootstrap, styling a button is as simple as adding the
<button type="button" class="btn">My Button</button>
The simple button component I use in many of my Vue/Bootstrap projects is this:
<template> <button v-bind="$attrs" v-on="$listeners" class="btn" type="button"> <slot></slot> </button> </template>
This just creates a simple button with a single default class of
btn. It allows all attributes and events to be passed into it.
Bringing it into a global components is as simple as this:
import btn from '@/components/ui/btn.vue'; Vue.component('btn', btn);
Then it can be used as simply as this:
Is a button component necessary?
So why would we need a whole Vue component when we could simply just add a class to a normal
button tag? Well, the main objective for me is to avoid writing
type="button" for any non-submit buttons I have. Often times in web apps or pages, links are used, when
button tags are actually more semantically correct. A
button tag is for actions, links are for navigation. If we want to submit a form, use a button. If you want to navigate to the
About Us page, use a link. Web apps (especially single page web apps) tend to have more actionable content than navigation in certain cases. For example, we may have a button that triggers a login modal instead of navigating to a login page. We could have a dropdown menu for an online file manager that would have actions such as copy, paste, move, delete, rename, etc.
In these cases, the
button tag is more appropriate to use than links. Also, in these cases, there are no forms involved. Since the default
type attribute for a button is
submit, I would find myself continually writing
type="button" for so many of my
button elements. At a certain point, I realized that I wanted my buttons to have a default type of
button instead of
submit to avoid this repetition. This was the main motivation for the simple button component. Since it accepts all the same attributes and events as a normal
button tag, we have an easy Bootstrap button with no complicated props to maintain.