
Vue 3 Cheats
Vue.js 3 is a progressive JavaScript framework for building user interfaces on the web. It's designed to be incrementally adoptable and can easily scale between a library and a full-featured framework.
Why Choose Vue 3?
Vue 3 comes with several exciting features that make it an excellent choice for developers:
- Composition API: This new API provides a set of additive, function-based APIs that allow flexible composition of component logic.
- Faster rendering: Vue 3 features a faster virtual DOM and improved runtime performance.
- Improved TypeScript support: Vue 3's codebase is written in TypeScript, allowing for better TypeScript integration.
Getting Started with Vue 3
Here's a basic Vue 3 application setup:
const { createApp } = Vue
const app = createApp({
data() {
return {
message: 'Hello Vue 3!'
}
}
})
app.mount('#app')
State
ref() vs. reactive(): Which should you use?
The significant difference between ref() and reactive() is that the ref() function allows us to declare reactive state for objects and primitives, while reactive() only declares reactive state for objects.
reactive advantages
- access the state directly instead of with .value.
- backwards compatible.
ref() advantages
- use primitives
- update the entire object at once
- generally more flexible
- typescript support (if you use typescript)
provide/inject
avoids props drilling from parent to child.
App # provides state =>
| # const numbers = [4,6.9,3,7]
| # provide("numbers", numbers);
Parent
|
Child # <= Inject const numbers = inject("numbers");
|
GrandChild
|
GreatGrandChild # <= Inject const numbers = inject("numbers");
- advantage - great for reading state across components
- disadvantage - methods for modifying state need to be duplicated.
Best for read only.
Vue 3 Slots
See Vue 3 Slot blog post for more information.
Named Slots
You can have more than one slot in a component, but you have to name all others but one (the default)
<!-- <MyComponent> template -->
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
A parent who wants to use the named component slots needs to specify the name with a #{name} or no name for default, like:
<!-- <MyParent> template -->
<BaseLayout>
<template #header>
<h1>Here might be a page title</h1>
</template>
<template #default>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
</template>
<template #footer>
<p>Here's some contact info</p>
</template>
</BaseLayout>
Scoped Slots
<!-- <MyComponent> template -->
<div>
<slot :text="greetingMessage" :count="1"></slot>
</div>
<!-- <MyParent> template -->
<MyComponent v-slot="slotProps">
{{ slotProps.text }} {{ slotProps.count }}
</MyComponent>
<!-- destructuring also works -->
<MyComponent v-slot="{ text, count }">
{{ text }} {{ count }}
</MyComponent>