User: {{ username }}
Count: {{ count }}, Doubled: {{ doubled }}
> `` is syntactic sugar for Composition API: it allows you to write Composition API code directly at the top level of ``, without manually `return`ing, and all top-level variables and functions are automatically exposed to the template. This is currently the most recommended single-file component syntax in Vue3. ### Reactivity System: Proxy Replacing defineProperty Vue2's reactivity was based on `Object.defineProperty`, which had two fundamentally unsolvable problems: inability to listen for newly added object properties, and inability to listen for array index assignments. Vue3 uses `Proxy` to fundamentally solve both problems. ## Example: ref and reactive import{ ref, reactive, watch } from 'vue' // ref: suitable for primitive types (number, string, boolean) // Access and modify values through .value const count = ref(0) count.value=10 // reactive: suitable for objects and arrays // Access properties directly, no need for .value const user = reactive({ name:'TUTORIAL', age:18, skills:['vue','typescript'] }) // Vue3 can directly add new properties to objects, reactivity works normally user.email='tutorial@example.com'// In Vue2 this operation would not trigger view updates // Can also directly modify array elements user.skills='vue3'// In Vue2 this operation would not trigger view updates // Watch for reactive data changes watch(count,(newVal, oldVal)=>{ console.log(`count changed from ${oldVal} to ${newVal}`) }) ### Composables Composables are the standard way to reuse stateful logic in Vue3, similar to custom Hooks in React. By convention, they are named with `use` prefix, extracting a complete piece of reactive logic into an independent function that can be reused across multiple components. ## Example: Custom Composable // File path: composables/useCounter.js // Encapsulates counter logic, any component can reuse it import{ ref, computed } from 'vue' export function useCounter(initialValue =0){ const count = ref(initialValue)// internal reactive state const doubled = computed(()=> count.value*2)// derived state function increment(){ count.value++} function decrement(){ count.value--} function reset(){ count.value= initialValue } // Return states and methods to be exposed externally return{ count, doubled, increment, decrement, reset } } ## Example: Using Composable in Component import { useCounter } from './composables/useCounter' // Destructure and use directly, reactivity is preserved const { count, doubled, increment, decrement, reset } = useCounter(10)Current value: {{ count }}, Doubled: {{ doubled }}
### New Built-in Components Vue3 adds three built-in components that solve three high-frequency scenarios in frontend development. | Component | Problem Solved | Typical Use Cases | | --- | --- | --- | | Fragment | Vue2 required component templates to have a single root node; Fragment allows multiple root nodes to coexist (no need for extra wrapper div) | List item components, reducing unnecessary DOM hierarchy | | Teleport | Renders component HTML to any specified position in the DOM, breaking through parent component's CSS stacking context limitations | Global Modal dialogs, Toast notifications, floating toolbars | | Suspense | Elegantly displays fallback content before async components finish loading, unified handling of async waiting states | Skeleton screens for lazy-loaded components, Loading during route transitions | ## Example: Teleport for Global Modal import { ref } from 'vue' const showModal = ref(false)This is a global modal
Loading...
### Tree-shaking Support
Vue3 changed all global APIs to named exports, working with Tree-shaking capabilities of bundlers like Vite / webpack, so unused APIs are not included in the final bundle.
## Example: On-demand API Import
// Vue2: All APIs accessed through global Vue object, cannot tree-shake
// Vue.nextTick(...)
// Vue.set(obj, 'key', value)
// Vue3: Import on demand, only includes functions actually used during bundling
import{ ref, computed, watch, nextTick, onMounted } from 'vue'
// Only these APIs are imported, others unused (like watchEffect, provide, etc.) won't enter the bundle
### Lifecycle Hooks
Vue3's Composition API lifecycle hooks all start with `on` and are called within `setup`.
| Vue2 Options | Vue3 Composition | Trigger Timing |
| --- | --- | --- |
| `beforeCreate` | β (setup itself replaces this) | Before instance initialization |
| `created` | β (setup itself replaces this) | After instance creation completes |
| `beforeMount` | `onBeforeMount` | Before mounting |
| `mounted` | `onMounted` | After mounting completes, DOM accessible |
| `beforeUpdate` | `onBeforeUpdate` | Before data update, DOM re-render |
| `updated` | `onUpdated` | After DOM re-render completes |
| `beforeDestroy` | `onBeforeUnmount` | Before component destruction (name changed) |
| `destroyed` | `onUnmounted` | After component destruction completes (name changed) |
## Example: Lifecycle Hook Usage
import { ref, onMounted, onUnmounted } from 'vue'
const timer = ref(null)
const count = ref(0)
// Executed after component mounts (DOM can be safely manipulated)
onMounted(() => {
console.log('Component mounted')
// Start timer, increment count every second
timer.value = setInterval(() => {
count.value++
}, 1000)
})
// Executed when component unmounts (cleanup side effects to prevent memory leaks)
onUnmounted(() => {
clearInterval(timer.value)
console.log('Timer cleared')
})
Running for: {{ count }} seconds
### Complete TypeScript Support Vue3's core library is completely rewritten in TypeScript, providing precise type inference. With ``, you can use TypeScript directly in single-file components without additional configuration. ## Example: Using TypeScript in script setup import { ref, computed } from 'vue' // Interface defining data structure within component interface User { id: number name: string email?: string } // ref infers type from initial value automatically, or can be explicitly specified const user = ref({ id: 1, name: 'TUTORIAL', }) // defineProps: declare and infer props types const props = defineProps() // defineEmits: declare and type-check custom events const emit = defineEmits() const displayName = computed(() => user.value.name.toUpperCase()) function handleUpdate() { emit('update', 42) } * * * ## Application Areas As a complete frontend framework ecosystem, Vue3 covers a wide range of scenarios from single-page applications to server-side rendering, from Web to mobile. ### Single Page Application (SPA) This is the most classic use case for Vue3. Combined with Vue Router 4 for frontend routing and Pinia (Vue3's officially recommended state management library, replacing Vuex) for global state management, complete single-page applications can be built. Typical project types: enterprise admin systems, data dashboards, e-commerce platforms. ### Server-Side Rendering (SSR) and Static Site Generation (SSG) Nuxt 3 is a full-stack framework based on Vue3, deeply integrating SSR and SSG capabilities. It automatically handles the complexity of server-side rendering, allowing developers to build SEO-friendly applications just like writing ordinary Vue components. Applicable scenarios: content websites, blogs, documentation sites, marketing landing pages. ### Mobile and Cross-platform uni-app supports using Vue3 syntax to simultaneously develop WeChat mini programs, Alipay mini programs, H5, and Apps (iOS/Android). Ionic + Vue3 is suitable for building high-quality hybrid mobile applications. ### Desktop Applications Electron + Vue3 (via toolchains like electron-vite) can package Vue3 applications into cross-platform desktop programs. Tauri + Vue3 is a popular alternative in recent years, using Rust as the backend for smaller application size and better performance. ### UI Component Library Ecosystem The Vue3 ecosystem has a wealth of mature component libraries to choose from: | Component Library | Positioning | Applicable Scenarios | | --- | --- | --- | | Element Plus | PC desktop component library, Element U
YouTip