Component Basics

Vue components are independent and reusable custom elements that can be displayed in a web app.

A Vue component is referred to as a Single File Component (SFC for short) because it resides in a dedicated file. SFC files are typically capitalized and end in .vue.  For organizational purposes, except for /src/App.vue, we put SFC files in /src/components.

A SFC file typically contains the following structure.

<script>
  // JS code that defines the data and method used by the component
</script>

<template>
  //HTML code that is rendered in the app
</template>

<style>
  //CSS that stylizes the HTML in the template
</style>

Defining a Logo Component

Below is an example of a component that renders the following logo.

We define the component in a file named Logo.vue and place the file in /src/components.  This component consists of HTML code in the template tags and some CSS in the style tags but does not utilize data or methods so does not contain/require the script tags.

<template>
  <div id="logo">
    <div id="title">Vue</div>
    <div id="subtitle">Components</div>
    <img alt="Vue logo" src="../assets/logo.png"/>
  </div>
</template>

<style>
#logo {
  aspect-ratio: 1 / 1;
  width: 15vh;
  background-color: lightgray;
  border-radius: 100px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
#title {
  font-size: 2vh;
}
#subtitle {
  font-size: 1.2vh;
}
img {
  display: inline-block;
  width: 50%;
}
</style>

Using the Logo Component

To use one component in another component we must do the following:

  1. Import the component
  2. Specify that the imported object is a component
  3. Use the component in the template

For example, to display the Logo component in the App.vue component we write the following in App.vue.

<script>
  import Logo from './components/Logo.vue'
</script>

<template>
  <Logo></Logo>
</template>

 

© 2023, Eric.