亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
What Is the Composition API?
Getting Started: setup() and Reactivity
1. Using ref() for Reactive Values
2. Using reactive() for Objects
Computed Properties and Watchers
1.computed computed() for Derived State
2. watch() and watchEffect() for Side Effects
Lifecycle Hooks in Composition API

Vue 3's Composition API is a game-changer for building scalable and maintained Vue applications. Unlike the Options API (used in Vue 2), which organizes code by options like data , methods , and computed , the Composition API lets you organize logic by feature or concern—making it easier to manage complex components and reuse code.

Vue 3 Composition API: A Comprehensive Tutorial

If you're coming from React or just want more flexibility in how you structure your Vue components, the Composition API is worth mastering. In this tutorial, we'll walk through everything you need to know—from the basics to advanced patterns—with practical examples.


What Is the Composition API?

The Composition API is a set of APIs that allow you to define component logic using imported functions instead of declaring options. It's centered around the setup() function (or <script setup></script> syntax), where you can use reactive variables, computed properties, watchers, and lifecycle hooks in a more flexible way.

Vue 3 Composition API: A Comprehensive Tutorial

Key benefits:

  • Better logic organization (group related code together)
  • Easier code reuse with composable functions
  • Improved TypeScript support
  • More control over reactivity

Note: The Composition API is not a replacement for the Options API—it's an alternative. You can use both in the same project.

Vue 3 Composition API: A Comprehensive Tutorial

Getting Started: setup() and Reactivity

Every Composition API component starts with the setup() function. This runs before the component is created and is where you define reactive state and logic.

1. Using ref() for Reactive Values

ref() creates a reactive reference to a value. It works for primitives (strings, numbers) and objects.

 <script>
import { ref } from &#39;vue&#39;

export default {
  setup() {
    const count = ref(0)

    const increment = () => {
      count.value  
    }

    return {
      count,
      Increment
    }
  }
}
</script>

<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

Important: Always use .value when accessing or modifying a ref inside setup() . In templates, Vue automatically unwraps it.

2. Using reactive() for Objects

reactive() makes an entire object reactive. No need for .value .

 import { reactive } from &#39;vue&#39;

setup() {
  const user = reactive({
    name: &#39;John&#39;,
    age: 30
  })

  const updateAge = () => {
    user.age  
  }

  return {
    user,
    updateAge
  }
}
 <template>
  <div>
    <p>{{ user.name }} is {{ user.age }} years old</p>
    <button @click="updateAge">Grow older</button>
  </div>
</template>

Use ref() for primitives and single values, reactive() for objects. But ref() also works for objects and is often preferred due to better TypeScript inference.


Computed Properties and Watchers

1.computed computed() for Derived State

Just like in the Options API, computed() creates a cached value based on reactive dependencies.

 import { ref, calculated } from &#39;vue&#39;

setup() {
  const firstName = ref(&#39;John&#39;)
  const lastName = ref(&#39;Doe&#39;)

  const fullName = computed(() => {
    return `${firstName.value} ${lastName.value}`
  })

  return { firstName, lastName, fullName }
}
 <template>
  <p>Full Name: {{ fullName }}</p>
</template>

2. watch() and watchEffect() for Side Effects

watch() lets you react to changes in specific refs or reactive properties.

 import { ref, watch } from &#39;vue&#39;

const count = ref(0)

watch(count, (newVal, oldVal) => {
  console.log(`Count changed from ${oldVal} to ${newVal}`)
})

watchEffect() runs immediately and automatically tracks dependencies:

 import { ref, watchEffect } from &#39;vue&#39;

const id = ref(1)

watchEffect(() => {
  console.log(&#39;Fetching user with id:&#39;, id.value)
  // Auto-runs when `id` changes
})

Use watch() when you need old/new values or async logic. Use watchEffect() for simpler side effects.


Lifecycle Hooks in Composition API

Lifecycle hooks are imported and used directly inside setup() .

 import {
  onMounted,
  onUpdated,
  onUnmounted
} from &#39;vue&#39;

setup() {
  onMounted(() => {
    console.log(&#39;Component mounted&#39;)
  })

  onUpdated(() => {
    console.log(&#39;Component updated&#39;)
  })

  onUnmounted(() => {
    console.log(&#39;Component unmounted&#39;)
  })

  return {}
}

Available hooks:

  • onBeforeMount
  • onMounted
  • onBeforeUpdate
  • onUpdated
  • onBeforeUnmount
  • onUnmounted
  • onErrorCaptured
  • onRenderTracked , onRenderTriggered (debugging)

Vue 3.2 introduced <script setup> , a syntactic sugar that makes the Composition API cleaner and more concise.

Just add setup to the script tag—no need to write setup() or return .

 <script setup>
import { ref, computed, onMounted } from &#39;vue&#39;

const count = ref(0)
const double = computed(() => count.value * 2)

const increment = () => count.value  

onMounted(() => {
  console.log(&#39;Component is ready!&#39;)
})
</script>

<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Double: {{ double }}</p>
    <button @click="increment"> </button>
  </div>
</template>

This is the recommended way to use the Composition API in modern Vue apps.


Creating Reusable Logic with Composables

One of the biggest advantages of the Composition API is the ability to extract logic into reusable functions—called composables .

For example, let's create a useMouse composable:

 //composables/useMouse.js
import { ref, onMounted, onUnmounted } from &#39;vue&#39;

export function useMouse() {
  const x = ref(0)
  const y = ref(0)

  const update = (e) => {
    x.value = e.clientX
    y.value = e.clientY
  }

  onMounted(() => {
    window.addEventListener(&#39;mousemove&#39;, update)
  })

  onUnmounted(() => {
    window.removeEventListener(&#39;mousemove&#39;, update)
  })

  return { x, y }
}

Now use it in any component:

 <script setup>
import { useMouse } from &#39;@/composables/useMouse&#39;

const { x, y } = useMouse()
</script>

<template>
  <div>Mouse: {{ x }}, {{ y }}</div>
</template>

You can create composables for:

  • Form handling
  • API calls ( useFetch )
  • Local storage ( useLocalStorage )
  • Dark mode toggle
  • And much more

When to Use Composition API?

  • ? Large components with lots of logic
  • ? Reusing logic across components
  • ? Working with TypeScript
  • ? Building complex UIs (dashboards, forms, real-time apps)

Stick with Options API if:

  • You're new to Vue
  • Your components are simple
  • Your team prefers familiar patterns

But for new projects, especially with Vue 3 , Composition API <script setup></script> is the way to go.


Final Tips

  • Always destroy ref s carefully—use .value when needed
  • Avoid returning unnecessary values from setup()
  • Name your composables with useX prefix
  • Use Vue DevTools for debugging reactivity
  • Prefer <script setup></script> for cleaner syntax

The Vue 3 Composition API gives you more power and organization than ever before. Once you get used to writing logic in functions instead of options, you'll wonder how you lived without it.

Basically, it's not just a new way to write Vue—it's a better way to think about component logic.

The above is the detailed content of Vue 3 Composition API: A Comprehensive Tutorial. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
How does React handle focus management and accessibility? How does React handle focus management and accessibility? Jul 08, 2025 am 02:34 AM

React itself does not directly manage focus or accessibility, but provides tools to effectively deal with these issues. 1. Use Refs to programmatically manage focus, such as setting element focus through useRef; 2. Use ARIA attributes to improve accessibility, such as defining the structure and state of tab components; 3. Pay attention to keyboard navigation to ensure that the focus logic in components such as modal boxes is clear; 4. Try to use native HTML elements to reduce the workload and error risk of custom implementation; 5. React assists accessibility by controlling the DOM and adding ARIA attributes, but the correct use still depends on developers.

Describe the difference between shallow and full rendering in React testing. Describe the difference between shallow and full rendering in React testing. Jul 06, 2025 am 02:32 AM

Shallowrenderingtestsacomponentinisolation,withoutchildren,whilefullrenderingincludesallchildcomponents.Shallowrenderingisgoodfortestingacomponent’sownlogicandmarkup,offeringfasterexecutionandisolationfromchildbehavior,butlacksfulllifecycleandDOMinte

What is the significance of the StrictMode component in React? What is the significance of the StrictMode component in React? Jul 06, 2025 am 02:33 AM

StrictMode does not render any visual content in React, but it is very useful during development. Its main function is to help developers identify potential problems, especially those that may cause bugs or unexpected behavior in complex applications. Specifically, it flags unsafe lifecycle methods, recognizes side effects in render functions, and warns about the use of old string refAPI. In addition, it can expose these side effects by intentionally repeating calls to certain functions, thereby prompting developers to move related operations to appropriate locations, such as the useEffect hook. At the same time, it encourages the use of newer ref methods such as useRef or callback ref instead of string ref. To use Stri effectively

Vue with TypeScript Integration Guide Vue with TypeScript Integration Guide Jul 05, 2025 am 02:29 AM

Create TypeScript-enabled projects using VueCLI or Vite, which can be quickly initialized through interactive selection features or using templates. Use tags in components to implement type inference with defineComponent, and it is recommended to explicitly declare props and emits types, and use interface or type to define complex structures. It is recommended to explicitly label types when using ref and reactive in setup functions to improve code maintainability and collaboration efficiency.

Server-Side Rendering with Next.js Explained Server-Side Rendering with Next.js Explained Jul 23, 2025 am 01:39 AM

Server-siderendering(SSR)inNext.jsgeneratesHTMLontheserverforeachrequest,improvingperformanceandSEO.1.SSRisidealfordynamiccontentthatchangesfrequently,suchasuserdashboards.2.ItusesgetServerSidePropstofetchdataperrequestandpassittothecomponent.3.UseSS

A Deep Dive into WebAssembly (WASM) for Front-End Developers A Deep Dive into WebAssembly (WASM) for Front-End Developers Jul 27, 2025 am 12:32 AM

WebAssembly(WASM)isagame-changerforfront-enddevelopersseekinghigh-performancewebapplications.1.WASMisabinaryinstructionformatthatrunsatnear-nativespeed,enablinglanguageslikeRust,C ,andGotoexecuteinthebrowser.2.ItcomplementsJavaScriptratherthanreplac

Vue CLI vs Vite: Choosing Your Build Tool Vue CLI vs Vite: Choosing Your Build Tool Jul 06, 2025 am 02:34 AM

Vite or VueCLI depends on project requirements and development priorities. 1. Startup speed: Vite uses the browser's native ES module loading mechanism, which is extremely fast and cold-start, usually completed within 300ms, while VueCLI uses Webpack to rely on packaging and is slow to start; 2. Configuration complexity: Vite starts with zero configuration, has a rich plug-in ecosystem, which is suitable for modern front-end technology stacks, VueCLI provides comprehensive configuration options, suitable for enterprise-level customization but has high learning costs; 3. Applicable project types: Vite is suitable for small projects, rapid prototype development and projects using Vue3, VueCLI is more suitable for medium and large enterprise projects or projects that need to be compatible with Vue2; 4. Plug-in ecosystem: VueCLI is perfect but has slow updates,

How to manage component state using immutable updates in React? How to manage component state using immutable updates in React? Jul 10, 2025 pm 12:57 PM

Immutable updates are crucial in React because it ensures that state changes can be detected correctly, triggering component re-rendering and avoiding side effects. Directly modifying state, such as push or assignment, will cause React to be unable to detect changes. The correct way to do this is to create new objects instead of old objects, such as updating an array or object using the expand operator. For nested structures, you need to copy layer by layer and modify only the target part, such as using multiple expansion operators to deal with deep attributes. Common operations include updating array elements with maps, deleting elements with filters, adding elements with slices or expansion. Tool libraries such as Immer can simplify the process, allowing "seemingly" to modify the original state but generate new copies, but increase project complexity. Key tips include each

See all articles