How to use ref and reactive in Vue 3 with script setup?
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.
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.

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:

<script setup> import { ref } from 'vue' 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.

for example:
<script setup> import { reactive } from 'vue' const user = reactive({ name: 'Alice', 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(''), password: '' })
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

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 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

SuspenseinVue3simplifieshandlingasynccomponentsbymanagingloadingstatesandintegratingerrorhandling.1.Itwrapsasynccontentanddisplaysfallbackcontentlikespinnersuntilthecomponentloads.2.YoudefineasynccomponentsusingdefineAsyncComponentandwraptheminaSuspe

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

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

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.

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,

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