Components
Learn the fundamentals of Vue.js components’s template, script, style, event, props, and directives.
We'll cover the following...
Vue components are reusable blocks in Vue applications that encapsulate specific functionality and user interface elements. Each component can have its own properties, methods, events, and templates that define the component’s HTML markup, making it easy to reuse code across different parts of an application.
Once a component is defined, it can be used in other parts of the application by adding its name as a custom HTML tag. Components can also be nested inside other components, allowing for the creation of complex user interfaces with a high degree of modularity and reusability.
Basic architecture of a Vue component
A Vue component typically consists of three sections—template, script, and style—as shown in the image below:
The single-page application (SPA) widget is a browser-based development environment that allows us to write, edit, and run code conveniently. It will be used throughout this course to enhance understanding and interactivity.
Below is an example of an SPA that contains code for a basic Vue application, demonstrating how components can be combined to create a page. To test it, simply click the “Run” button and the built-in compiler will generate the application. Once it’s finished, we can view the pages on the embedded display or through the provided link.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="icon" href="/favicon.ico"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vite App</title> </head> <body> <div id="app"></div> <script type="module" src="/src/main.ts"></script> </body> </html>
Props
Component props can be thought of as a conduit for passing data from a parent component to the child component.
To maintain data integrity and consistent behavior through the app, Vue requires that all expected component props are declared within the component. This can be done using the defineProps
macro.
<template><div><p>{{ greetings }}</p></div></template><script setup lang="ts">defineProps({greetings: String})</script>
The code above shows the HelloWorldWithGreeting
component declaration, which is used in the SPA as an option within the DynamicComponent
. This ...