The Anatomy of a Vue 3 Component
<p>V</p>
<p>ue 3 has made significant progress and reached a strong level of maturity with Composition API & Script Setup being the recommended and widely adopted syntax for writing our components. This differs from the options API, which was the preferred approach in Vue 2.</p>
<p>Let's explore together all the ingredients of a Vue 3 component using Composition API and Script Setup.</p>
<p><strong>tl;dr </strong></p>
<pre>
<script setup>
import {
ref,
reactive,
defineAsyncComponent,
computed,
watch,
onMounted,
} from "vue";
import useComposable from "./composables/useComposable.js";
import TheComponent from "./components/TheComponent.vue";
const AsyncComponent = defineAsyncComponent(() =>
import("./components/AsyncComponent.vue")
);
console.log("Equivalent to created hook");
onMounted(() => {
console.log("Mounted hook called");
});
const enabled = ref(true);
const data = reactive({ variable: false });
const props = defineProps({
elements: Array,
counter: {
type: Number,
default: 0,
},
});
const { composableData, composableMethod } = useComposable();
const isEmpty = computed(() => {
return props.counter === 0;
});
watch(props.counter, () => {
console.log("Counter value changed");
});
const emit = defineEmits(["event-name"]);
function emitEvent() {
emit("event-name");
}
function getParam(param) {
return param;
}
</script>
<template>
<div class="wrapper">
<TheComponent />
<AsyncComponent v-if="data.variable" />
<div
class="static-class-name"
:class="{ 'dynamic-class-name': data.variable }"
>
Dynamic attributes example
</div>
<button @click="emitEvent">Emit event</button>
</div>
</template>
<style scoped>
.wrapper {
font-size: 20px;
}
</style></pre>
<h1>Script Setup</h1>
<p>A Single File Component still consists of 3 parts. The template, the styles and the script. The two former are almost identical between vue 2 and vue 3, with the latter being completely revamped to the so-called script setup syntax. Declararion is simply adding the setup keyword in the script tag.</p>
<p><a href="https://fadamakis.com/the-anatomy-of-a-vue-3-component-285eadadea89">Website</a></p>