Performance: Defining components
This affects initial page load speed and rendering performance by controlling how Vue processes and renders UI parts.
<script setup> import MyButton from './MyButton.vue' </script> <template> <MyButton /> <MyButton /> <MyButton /> </template>
<script setup> const MyButton = { template: `<button>Click me</button>` } </script> <template> <MyButton /> <MyButton /> <MyButton /> </template>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Inline component definitions recreated each render | High (many nodes recreated) | Multiple reflows per render | High paint cost due to frequent DOM updates | [X] Bad |
| Imported single component reused multiple times | Low (nodes reused) | Single reflow per update | Lower paint cost due to efficient updates | [OK] Good |
<script setup>?<script setup> syntax<script setup> is a special syntax that allows direct use of variables without export default.<script setup> correctly<script setup> and uses it in the template, which is correct.<script setup> uses direct variable declaration [OK]<script setup>
import { ref } from 'vue'
const count = ref(0)
function increment() {
count.value++
}
</script>
<template>
<button @click="increment">Clicked {{ count }} times</button>
</template>count is a reactive reference starting at 0. Using count.value++ updates it reactively.count.<script setup>
const props = defineProps({
title: String
})
function showTitle() {
console.log(props.title.toUpperCase())
}
showTitle()
</script>
<template>
<h1>{{ title }}</h1>
</template>defineProps({ title: String }) declares title without required: true or default value, so props.title can be undefined.showTitle(), props.title.toUpperCase() assumes title is a string, but calling toUpperCase() on undefined causes a runtime error.toUpperCase() on a possibly undefined prop -> Option Duser prop object with name and age, and displays "Name: [name], Age: [age]". Which is the best way to define and use this prop in a <script setup> component?user is an object containing name and age, so define it as an Object type and mark required if needed.props.user.name and props.user.age to display the values inside the template.Pass the test and this pattern moves unknown