Sobes.tech
Junior

What sections does a Vue component consist of?

sobes.tech AI

Answer from AI

A Vue component consists of three main sections:

  • <template>: Contains the markup (HTML) that defines the structure and appearance of the component. This section uses Vue template syntax for data binding, directives, and logic display.
  • <script>: Contains JavaScript code that defines the component's logic: state (data), methods, computed properties, lifecycle hooks, etc.
  • <style>: Contains CSS code for styling the component. Styling can be local (scoped) or global. Scoped style ensures styles are applied only to this component's elements, preventing conflicts.

Example of a component structure in a single-file component (.vue):

<template>
  <!-- Component's HTML markup -->
  <div>
    <h1>{{ message }}</h1>
    <button @click="greet">Click me</button>
  </div>
</template>

<script>
  // Component's JavaScript logic
  export default {
    data() {
      return {
        message: 'Hello, world!'
      }
    },
    methods: {
      greet() {
        alert('Hello!');
      }
    }
  }
</script>

<style scoped>
  /* Component's CSS styles (scoped - limited to this component) */
  h1 {
    color: blue;
  }
</style>