Table of Contents
ref : suitable for basic types and independent responsive values
reactive : More suitable for objects and nested structures
How to choose ref or reactive?
Tips: Use ref and reactive in combination
Home Web Front-end Vue.js How to use ref and reactive in Vue 3 with script setup?

How to use ref and reactive in Vue 3 with script setup?

Jul 26, 2025 am 06:21 AM
Combined API Vue 3

ref is suitable for basic types and independent values, and requires .value operations; reactive is suitable for objects and nested structures, and direct attribute operations. 1. Ref is used in scenarios where basic types or cross-functional passes. 2. Reactive is used for objects or associated properties. 3. Note that reactive split assignments will lose responsiveness. 4. Ref and reactive can be used in combination to flexibly handle complex scenarios.

How to use ref and reactive in Vue 3 with script setup?

In Vue 3's script setup syntax, ref and reactive are two very commonly used responsive APIs that are used to create responsive data. Although the functions are similar, there are some differences in usage scenarios and details. If used correctly, it can improve code clarity and performance.

How to use ref and reactive in Vue 3 with script setup?

ref : suitable for basic types and independent responsive values

ref is best suited for handling basic types (such as strings, numbers, booleans), and can also be used in objects or arrays. It accesses or modifies values through the .value property.

For example:

How to use ref and reactive in Vue 3 with script setup?
 <script setup>
import { ref } from &#39;vue&#39;

const count = ref(0)

function increment() {
  count.value  
}
</script>

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

A few points to note:

  • When used in templates, you do not need to add .value , Vue will be automatically unpacked.
  • If you need to judge or assign values in logic, remember to add .value .
  • ref creates a "mutable reference" that is suitable when you need to track the state of a variable individually.

reactive : More suitable for objects and nested structures

reactive is generally used for objects or arrays. It returns a responsive proxy object, which is closer to the operation method of ordinary JS objects.

How to use ref and reactive in Vue 3 with script setup?

for example:

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

const user = reactive({
  name: &#39;Alice&#39;,
  age: 25
})

function updateAge() {
  user.age  
}
</script>

<template>
  <div>{{ user.name }} is {{ user.age }}</div>
  <button @click="updateAge">Increase Age</button>
</template>

Feature summary:

  • No .value is needed, just operate the attributes directly.
  • Cannot be used for primitive types (will fail silently).
  • If you have a set of relevant states to manage, using reactive is more intuitive.

How to choose ref or reactive?

Depend on your data structure and usage habits:

  • ✅Use ref as :

    • Data is the basic type.
    • Need to be passed between multiple functions or components.
    • Want to keep the feeling of simple variables.
  • ✅Use reactive as :

    • Data is an object or nested structure.
    • Relevant between multiple attributes.
    • I hope the writing method is closer to native JS objects.

However, it should be noted that if the object wrapped in reactive is disassembled and assigned to other variables, it may lose its responsiveness. It is recommended to use ref at this time.


Tips: Use ref and reactive in combination

Sometimes you can mix the two for better results. For example:

 const form = reactive({
  username: ref(&#39;&#39;),
  password: &#39;&#39;
})

In this way, username is ref and password is a normal field. Although it is a bit advanced, it is useful in some scenarios, such as trying to make username referenced elsewhere and remain responsive.


Basically that's it. Understand the difference between ref and reactive , and select the model according to actual needs, you can write clear and efficient Vue 3 responsive code.

The above is the detailed content of How to use ref and reactive in Vue 3 with script setup?. 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 Article

RimWorld Odyssey How to Fish
1 months ago By Jack chen
Can I have two Alipay accounts?
1 months ago By 下次还敢
Beginner's Guide to RimWorld: Odyssey
1 months ago By Jack chen
PHP Variable Scope Explained
3 weeks ago By 百草

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
1506
276
Detailed explanation of the combined API in Vue3: a better way to write components Detailed explanation of the combined API in Vue3: a better way to write components Jun 18, 2023 pm 02:28 PM

Detailed explanation of the combined API in Vue3: a better way to write components Vue3 introduces a new combined API, which helps to better organize and write components. This article will introduce the use and advantages of these APIs in detail. setupIn Vue3, a new setup function is added to the component options, which is a function that is executed before the component is instantiated. In the setup function, you can do some data preparation work, and you can also return some data or functions for template use. In the setup function, we can use two

Learn the combined API in Vue 3 to better organize and manage component code Learn the combined API in Vue 3 to better organize and manage component code Sep 09, 2023 am 08:45 AM

Learn the composed API in Vue3 to better organize and manage component code Vue3 is the latest version of the Vue framework. It introduces many exciting new features and improvements, the most notable of which is the composed API. Composable APIs enable us to better organize and manage component code, and better reuse and share logic. In Vue2, we use OptionsAPI to define and organize components. Each component contains an options object, which contains the component's data, methods, lifecycle

How does  in Vue 3 help manage asynchronous components and their loading states? How does in Vue 3 help manage asynchronous components and their loading states? Jun 10, 2025 am 12:07 AM

SuspenseinVue3simplifieshandlingasynccomponentsbymanagingloadingstatesandintegratingerrorhandling.1.Itwrapsasynccontentanddisplaysfallbackcontentlikespinnersuntilthecomponentloads.2.YoudefineasynccomponentsusingdefineAsyncComponentandwraptheminaSuspe

Combined API functions in Vue3: a new way of writing components Combined API functions in Vue3: a new way of writing components Jun 19, 2023 am 08:45 AM

Combined API functions in Vue3: A new way of writing components Vue is a popular JavaScript framework that has gradually occupied an important position in the field of web development with its intuitive development experience, efficient performance and elegant API design. Recently, Vue has updated its latest version, Vue3, and one of the most eye-catching features is the combined API function, which brings developers a new way of writing components. What are combined API functions? In Vue2, developers mainly use the options API

How does the  syntax in Vue 3 simplify component authoring within the Composition API? How does the syntax in Vue 3 simplify component authoring within the Composition API? Jun 11, 2025 am 12:10 AM

Vue3’sCompositionAPIimprovescomponentdevelopmentbyofferingamoreflexibleandintuitiveapproachcomparedtotheOptionsAPI.1.Itallowsmorenaturalcodeorganizationbygroupingrelatedlogictogetherinsteadofsplittingacrossdata,methods,computed,andwatch.2.Itenablesre

What are the considerations for migrating a Vue 2 application to Vue 3? What are the considerations for migrating a Vue 2 application to Vue 3? Jun 08, 2025 am 12:16 AM

Migrating to Vue3 requires starting from four aspects: compatibility checking, responsive system changes, component communication adjustment, and building tool upgrade. First, check whether the project dependencies support Vue3, especially core libraries such as Vuex and VueRouter, and consider using @vue/compat for gradual migration; second, the responsive system is implemented by Proxy, and ref/reactive needs to explicitly declare responsive data, replacing Vue.set; third, the life cycle hook is changed to onBeforeMount, onMounted, etc., and it is necessary to explicitly import and declare props/emits; fourth, if TypeScript is used, the configuration file and toolchain support need to be updated. It is recommended to complete it first.

Key differences between Vue 2 and Vue 3? Key differences between Vue 2 and Vue 3? Jul 09, 2025 am 01:29 AM

Vue3 has improved in many key aspects compared to Vue2. 1.Composition API provides a more flexible logical organization method, allowing centralized management of related logic, while still supporting Vue2's Options API; 2. Better performance and smaller package size, the core library is reduced by about 30%, the rendering speed is faster and supports better tree shake optimization; 3. The responsive system uses ES6Proxy to solve the problem of unable to automatically track attribute addition and deletion in Vue2, making the responsive mechanism more natural and consistent; 4. Built-in better support for TypeScript, support multiple node fragments and custom renderer API, improving flexibility and future adaptability. Overall, Vue3 is a smooth upgrade to Vue2,

How can TypeScript be effectively integrated into a Vue 3 project, particularly with the Composition API? How can TypeScript be effectively integrated into a Vue 3 project, particularly with the Composition API? Jun 13, 2025 am 12:13 AM

TypeScriptenhancesVue3projectswithtypesafetyandimprovedtooling,especiallywhenusingtheCompositionAPI.TosetupVue3withTypeScript,useViteorVueCLI,installrequiredpackages,createatsconfig.jsonfile,andrename.jsfilesto.ts.WhenusingtheCompositionAPI,definepro

See all articles