YouTip LogoYouTip

Vue3 Introduction

Vue3 is a progressive framework for building user interfaces. Progressive means you can introduce only the parts of Vue you need for your project: from simple page interaction enhancements to building complete single-page applications (SPA), and even server-side rendering (SSR) applications, Vue3 can handle them all. Vue3 is a progressive JavaScript frontend framework led by Evan You, officially released on September 18, 2020, codenamed One Piece. Compared to Vue2, Vue3 has completely rewritten its core architecture: the reactivity system was upgraded from `Object.defineProperty` to `Proxy`, the Composition API was introduced, and performance, TypeScript support, bundle size, and other aspects were comprehensively improved. !(#) > Vue3's official positioning is: **a framework that is easy to get started with, yet capable enough to support complex projects**. It doesn't enforce a specific architecture like Angular, nor does it require extensive manual optimization like React, but instead finds a balance between ease of use and capability. ### The Essential Difference Between Vue3 and Vue2 Vue3 is not a patch upgrade to Vue2, but a complete rewrite. | Comparison Item | Vue2 | Vue3 | | --- | --- | --- | | Reactivity Principle | `Object.defineProperty`, cannot listen for added properties or array index changes | `Proxy`, fully proxies all object operations, no above limitations | | Code Organization | Options API: data, methods, computed are separated | Composition API: code organized by logical concerns | | TypeScript Support | Adapted later, limited type inference | Core code rewritten in TypeScript, TS is a first-class citizen | | Bundle Size | Runtime approximately 20KB (gzip) | Supports Tree-shaking, on-demand bundling, minimum only 13.5KB | | Performance | Baseline | Initial rendering ~55% faster, update rendering ~133% faster, memory usage reduced by ~54% | | Component Template Root Node | Must have exactly one root element | Supports multiple root nodes (Fragment) | | Global API | Mounted on Vue constructor, multiple instances share state | Creates independent instances via `createApp`, more thorough isolation | * * * ## Core Features Vue3's improvements cover four dimensions: reactivity system, API design, compiler, and new built-in components. ### Composition API Composition API is the most important design change in Vue3. It solves the fundamental pain point of Options API in Vue2: **related logic is scattered across different options, making reuse difficult**. In Options API, data for a "user search" feature might be scattered across `data`, `methods`, `computed`, and `watch` options; while Composition API allows you to write all logic for the same feature together, then extract it as a reusable function (Composable). ## Example: Options API vs Composition API export default { data() { return { count: 0, // counter data username: 'tutorial' // username data } }, computed: { doubled() { // double of count return this.count * 2 } }, methods: { increment() { // increase count this.count++ } } } ## Example: Recommended Syntax (script setup sugar) import { ref, computed } from 'vue' // Reactive data declared directly, no need to return const count = ref(0) // ref wraps primitive types const username = ref('tutorial') // Computed properties const doubled = computed(() => count.value * 2) // Methods defined as functions directly function increment() { count.value++ // Note: values wrapped by ref need to be accessed via .value }

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) ## Example: Suspense Handling Async Component Loading
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
← Rust IntroTs Intro β†’