Functional Components and Props
Create a functional component in Vue.js 3 that accepts and uses props, demonstrating the difference from stateful components.
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
This is the HTML template part of the Vue component. It defines the structure of the output which includes a paragraph element that will be used to display the message prop passed to the component.
<script setup>
import { ref, onMounted } from 'vue';
defineProps({
message: String
});
const localState = ref('Local State');
onMounted(() => {
console.log('Component has been mounted!');
});
</script>
Within the script tag with 'setup' attribute, the component is defined using the Composition API. Here, 'defineProps' is used to define the 'message' prop that the component will accept. A local reactive state 'localState' is also declared with 'ref', it'll be managed internally by the component. The 'onMounted' lifecycle hook is used to log to the console when the component has been mounted.
<style scoped>
p {
font-size: 16px;
color: #333;
}
</style>
The style tag contains scoped CSS for this component, which means the styles defined here will only apply to this component. The styling is simple, targeting the paragraph element to adjust the font size and text color.