Vue Single File Components 🎯

beginner
5 min

Vue Single File Components 🎯

Welcome back to CodeYourCraft! Today, we're going to dive into one of the most powerful features of Vue.js - Single File Components (SFCs). These components are a unique blend of HTML, CSS, and JavaScript, making them incredibly practical for real-world projects. Let's get started!

What are Single File Components? 📝

Single File Components, or SFCs, are a Vue-specific syntax that allows us to write our components in a single file, combining HTML, CSS, and JavaScript. This makes our components easier to manage, test, and understand.

markdown
<template> <!-- HTML template goes here --> </template> <script> // JavaScript goes here export default { // Options object } </script> <style> // CSS goes here </style>

Creating a Simple SFC 💡

Let's create a simple SFC that displays a greeting message.

markdown
<template> <h1>Hello, World!</h1> </template> <script> export default { name: 'Greeting' } </script>

In this example, we have a template containing an h1 tag that displays "Hello, World!". The JavaScript section exports a component named Greeting.

Props and Events 📝

Props allow us to pass data from a parent component to a child component. On the other hand, events enable a child component to communicate back to its parent.

Here's an example of a child component that accepts a prop and emits an event:

markdown
<template> <button @click="onClick">{{ message }}</button> </template> <script> export default { props: { message: { type: String, default: 'Click me!' } }, methods: { onClick() { this.$emit('clicked', 'Message clicked!') } } } </script>

In this example, we have a child component with a button that displays a message and emits an event when clicked. The parent component can listen for this event and take action accordingly.

Quiz 💡

Quick Quiz
Question 1 of 1

What is the purpose of a Single File Component in Vue.js?

We hope you enjoyed learning about Single File Components in Vue.js! Stay tuned for more tutorials on CodeYourCraft. Happy coding! 🤘