Vue Component Example: Bootstrap Alert Wrapper

In this example, let’s create a wrapper around Bootstrap alerts.

This is how the code layout of bootstrap 4 alert box looks like

<div class="alert alert-warning alert-dismissible fade show" role="alert">
  <strong>Holy guacamole!</strong> You should check in on some of those fields below.
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    <span aria-hidden="true">&times;</span>
  </button>
</div>

We are looking to create a component of this alert box in Vue to simplify this. So that we can create a bootstrap alert in HTML with something like

<bootstrap-alert>Message body</bootstrap-alert>

Also to have the dismiss button functioning we need to use alert javascript plugin with bootstrap. We will handle it within Vue itself.

Here is how the component looks like

    Vue.component('bootstrap-alert',{
        template: `<div v-show="isVisible" class="alert alert-warning alert-dismissible fade show" role="alert">
            <slot></slot>
            <button @click="isVisible = false" type="button" class="close" data-dismiss="alert" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>`,

          data(){
              return{
                  isVisible: true
              }
          }
    });

We have created a component with name bootstrap-alert and created a template same as what bootstrap provides. To fill in the body we are using slot element.

Also we have created a data property isVisible which is true by default and on the click action of the button changes to false. v-show directive is used to hide the alert box.

Code:

https://github.com/tushargugnani/vue-examples/blob/master/bootstrap-alert.html

Working Demo:

https://tushargugnani.github.io/vue-examples/bootstrap-alert.html

tgugnani: Web Stuff Enthusiast.