DEV Community

R☭
R☭

Posted on

A quick Vue (Nuxt) component example.

A short introduction to create a reusable alert component.

Prequisites and setup

This is not a formal setup guide, but just the way i have it set up so it can be replicated. It is expected to have a Nuxt application running, if you want to know how to easily do that Nuxt installation.

  • Nuxt 2.14*
  • Node 14 (but Node > 10 should suffice)

The component

components/general/alert.vue (file name for the component)

<template>
  <div class="alert" :class="type">
    {{ message }}
  </div>
</template>

<script>
export default {
  name: 'alert',
  props: ['message', 'type']
}
</script>
Enter fullscreen mode Exit fullscreen mode

It is a single div component, which contains a message that is passed down as a props value. It also has a type props that is being used to set a class. the shorthand :class is being used (which does the same as v-bind:class).

Using the component

To use this component with dynamic values, you need to import it in a different component. Register it in the components object and then it is usable as a custom HTML element.

pages/index.vue (file name for the page file)

<template>
  <div class="page">
    <h1>Page title</h1>

    <alert :message="'Error Error!'" :type="'error'" />
  </div>
</template>

<script>
import Alert from '@/path/to/alert';

export default {
  name: 'basic-page',
  components: { Alert }
}
Enter fullscreen mode Exit fullscreen mode

In this example, we import Alert from '@/path/to/alert'; then we register it in components: { Alert }. Finally we use it as a custom HTML element. We use :message= to pass a String value.

(notice that we are using single quotes within the double quotes to specifically pass a String, if you want to pass down an object or a variable, do it like: :message="customMessage").

Finally in the same way we are passing the String error. which is then added as a class to the element.

The final HTML output will then be something like:

<div class="alert error">
  Error Error!
</div>
Enter fullscreen mode Exit fullscreen mode

By adding methods, computed values and fancier styling you can create components that are very flexible, small and are usable wherever you want in your application.

Top comments (0)