Challenge 2

Challenges are an opportunity to test what you have learned by interacting directly with live code.

For this challenge, you will create an alert-box component with a customizable style and text using slots and props. The alert box component should be based on the Bootstrap Alerts componentopen in new window.

NOTE

For this challenge, you will need to edit the HTML and JavaScript. The Bootstrap framework has already been added.

Solution

From the Bootstrap documentation, we can conclude the component's template will require a slot for the customizable text and a variant prop to specify the alert's style.

<div class="alert alert-[variant prop]" role="alert">
  <!-- slot output -->
</div>

For this challenge, we can use global registration to create the alert-box component. We declare that the variant attribute should be used as a prop using the props property. The template will contain a dynamic class attribute to set the alert's style using the variant prop. The <slot> element will be placed between the <div> tags to allow for custom content.

app.component('alert-box', {
  props: ['variant'],
  template: `
  <div class="alert" :class="'alert-' + variant" role="alert">
      <slot></slot>
  </div>
  `
})

In the HTML, we will use the alert-box component by calling the <alert-box> custom element and adding the variant attribute and content between the <alert-box> tags.

<alert-box variant="success">
  <strong>Yes!</strong> I did it.
</alert-box>