search
HomeWeb Front-endVue.jsVue3 responsive function comparison: toRef() vs toRefs()

Vue3 responsive function comparison: toRef() vs toRefs()

ref is a responsive API function that handles basic data types. The variables defined in setup can be declared Using

directly in the template variable data that has not been wrapped and processed by the responsive API does not have responsive capabilities

That is, the data is often modified in the logic , but the page will not be updated, so how to turn a non-responsive data into responsive data

You need to use toRef() and toRefs() These two componsition API

simply look at the concepts, which are often abstract and difficult to understand. You still need to start from specific examples

toRef() function

Function: Create a ref object whose value value points to a certain attribute value in another object, which is the same as the original object Related. [Related recommendations: vuejs video tutorial, web front-end development]

is to create a corresponding ref# based on an attribute on the responsive object. ##, the ref created in this way is synchronized with its source attribute, and has a reference relationship with the source object.

Changing the value of the source attribute will update the

ref Value

Syntax: const Variable name = toRef(source object, a property under the source object)

For example:

const name = toRef(person,'name')

Application: When you want to provide a certain attribute in the responsive object for external use separately, If you don't want to lose responsiveness, it can also be useful to pass a ref of a prop to a composed function

Disadvantages: toRef () can only process one attribute, but toRefs(source object) can be processed in batches at one time

<script setup>
import { reactive } from "vue";
const person = reactive({
   name:"川川",
   age: 18,
   job: {
     web: &#39;前端开发&#39;,
     trade: &#39;互联网&#39;
   } 
});
</script>

If you want to render data in the template, you can write like this

{{person.name}} -{{person.age}}-{{person.job.web}}-{{person.job.trade}}

If you don’t want to write so long in the template, you can deconstruct it first, as shown below

<script setup>
import { reactive } from "vue";
const person = reactive({
   name:"川川",
   age: 18,
   job: {
     web: &#39;前端开发&#39;,
     trade: &#39;互联网&#39;
   } 
});

const { name, age} = person;
const { web,trade} = person.job;
</script>

Then in the template, you can use variables directly, as shown below

{{name}}-{{age}}-{{web}}-{{trade}}

Now, if we want to modify the variable data, we will find that the data in the logic will be modified, but the data in the page will not be updated, that is, the responsiveness will be lost. For example: the following template, modify the name and age attributes respectively

<button @click="handleChangeAttrs">修改属性</button>

In the logic code

<script setup>
import { reactive } from "vue";
const person = reactive({
   name:"川川",
   age: 18,
   job: {
     web: &#39;前端开发&#39;,
     trade: &#39;互联网&#39;
   } 
});

const { name, age} = person;
const { web,trade} = person.job;

// 这样直接操作数据是无法修改的,因为它不是一个响应式数据,只是一个纯字符串,不具备响应式
function handleChangeAttrs() {
    name = "itclanCoder";
    age = 20;
}
</script>

If you want to modify the data, support responsiveness, and turn a non-responsive data into responsive data, you need to borrow

toRef(source Object, the specified attribute under the source object) function , as shown below

<script setup>
import { reactive,toRef } from "vue";
const person = reactive({
   name:"川川",
   age: 18,
   job: {
     web: &#39;前端开发&#39;,
     trade: &#39;互联网&#39;
   } 
});

// 想要修改指定哪个对象具备响应式,那么就使用toRef函数处理,toRef(源对象,源对象下的某个属性)
const name = toRef(person,&#39;name&#39;);  
const age = toRef(person,&#39;age&#39;);

// 经过了toRef的处理,修改变量的值,那么就需要xx.value
function handleChangeAttrs() {
    name.value = "itclanCoder";
    age.value = 20;
}
</script>

In the template, it is still as shown above

{{person}}
{{name}}-{{age}}-{{web}}-{{trade}}
<button @click="handleChangeAttrs">修改属性</button>

You will find that using

toRef() After function processing, non-responsive data will have the ability to respond to data, and the source data will also be synchronized

If it is only used for the display of pure data pages, there is no need to convert the data For responsive data, if you need to modify the data, you need to convert non-responsive data into responsive data

is implemented through the

toRef() function

The difference from ref

If you use

ref to process data, as shown below, use ref to process data, and the page can also achieve responsiveness and update of data. But it is different from toRef. There is a difference.

<script setup>
import { reactive,toRef } from "vue";
const person = reactive({
   name:"川川",
   age: 18,
   job: {
     web: &#39;前端开发&#39;,
     trade: &#39;互联网&#39;
   } 
});

// 使用ref
const name = ref(person.name);  
const age = toRef(person.age);

// 经过了toRef的处理,修改变量的值,那么就需要xx.value
function handleChangeAttrs() {
    name.value = "itclanCoder";
    age.value = 20;
}
</script>

Modify the data, the page data will be updated, but the source data will not be synchronized, modified, and there is no reference relationship,

refEquivalent to re-copying a copy of the data from the source objectref()What is received is a pure value

toRefs() function

toRef() can only process a certain attribute specified by the source object. If the source object has many attributes, it will be troublesome to use toRef() one by one.

Then this

toRefs () is very useful. It has the same function as toRef(). It can create multiple ref objects in batches, and can maintain synchronization with the source object and have a reference relationship.

Syntax:toRefs(source object),toRefs(person)

Such as the above sample code, modify it to

toRefs()shown

<script setup>
import { reactive,toRefs } from "vue";
const person = reactive({
   name:"川川",
   age: 18,
   job: {
     web: &#39;前端开发&#39;,
     trade: &#39;互联网&#39;
   } 
});

// 通过toRefs()批量处理,此时通过解构
const {name,age} = toRefs(person);  

// 经过了toRef的处理,修改变量的值,那么就需要xx.value
function handleChangeAttrs() {
    name.value = "itclanCoder";
    age.value = 20;
}
</script>

toRefs is useful when returning reactive objects from composed functions. Using this, the consumer component can destructure/unfold the returned object without losing responsiveness

import { toRefs } from "vue";
function useFeatureX() {
  const state = reactive({
    foo: 1,
    bar: 2
  })

  // 在返回时都转为ref
  return toRefs(state)
}

// 可以解构而不会失去响应性
const { foo, bar } = useFeatureX()

Notes

toRefs will only be on the source object when called Enumerable properties create ref. If you want to create a ref for a property that may not exist yet, use toRef

Why you need the toRef() and toRefs() functions

Purpose: Deconstruct the object without losing the responsiveness to facilitate the decomposition and diffusion of object data

Premise: Targeted at responsive objects (reactiveencapsulated) non-ordinary object

Note: Do not create a reactive type (that is a reactive thing), it itself is just a continuation Responsive, the ability to convert non-responsive data into responsive data through toRef or toRefs

Summary

This toRef() and toRefs() are very practical, both of which turn a non-responsive data into a responsive data Ability to maintain data synchronization with the source object and have a reference relationship. The former only supports the processing of single attribute data, while the latter supports batch processing of data

When the data is modified, the page data will be updated, these two# The ##composition API function is very practical. In actual business development, if it involves modifying the data on the page, then

will be used (learning video sharing:

vuejs introductory tutorial, Basic Programming Video)

The above is the detailed content of Vue3 responsive function comparison: toRef() vs toRefs(). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Vue.js vs. React: Scalability and MaintainabilityVue.js vs. React: Scalability and MaintainabilityMay 10, 2025 am 12:24 AM

Vue.js and React each have their own advantages in scalability and maintainability. 1) Vue.js is easy to use and is suitable for small projects. The Composition API improves the maintainability of large projects. 2) React is suitable for large and complex projects, with Hooks and virtual DOM improving performance and maintainability, but the learning curve is steeper.

The Future of Vue.js and React: Trends and PredictionsThe Future of Vue.js and React: Trends and PredictionsMay 09, 2025 am 12:12 AM

The future trends and forecasts of Vue.js and React are: 1) Vue.js will be widely used in enterprise-level applications and have made breakthroughs in server-side rendering and static site generation; 2) React will innovate in server components and data acquisition, and further optimize the concurrency model.

Netflix's Frontend: A Deep Dive into Its Technology StackNetflix's Frontend: A Deep Dive into Its Technology StackMay 08, 2025 am 12:11 AM

Netflix's front-end technology stack is mainly based on React and Redux. 1.React is used to build high-performance single-page applications, and improves code reusability and maintenance through component development. 2. Redux is used for state management to ensure that state changes are predictable and traceable. 3. The toolchain includes Webpack, Babel, Jest and Enzyme to ensure code quality and performance. 4. Performance optimization is achieved through code segmentation, lazy loading and server-side rendering to improve user experience.

Vue.js and the Frontend: Building Interactive User InterfacesVue.js and the Frontend: Building Interactive User InterfacesMay 06, 2025 am 12:02 AM

Vue.js is a progressive framework suitable for building highly interactive user interfaces. Its core functions include responsive systems, component development and routing management. 1) The responsive system realizes data monitoring through Object.defineProperty or Proxy, and automatically updates the interface. 2) Component development allows the interface to be split into reusable modules. 3) VueRouter supports single-page applications to improve user experience.

What are the disadvantages of VueJs?What are the disadvantages of VueJs?May 05, 2025 am 12:06 AM

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

Netflix: Unveiling Its Frontend FrameworksNetflix: Unveiling Its Frontend FrameworksMay 04, 2025 am 12:16 AM

Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.

Frontend Development with Vue.js: Advantages and TechniquesFrontend Development with Vue.js: Advantages and TechniquesMay 03, 2025 am 12:02 AM

Reasons for Vue.js' popularity include simplicity and easy learning, flexibility and high performance. 1) Its progressive framework design is suitable for beginners to learn step by step. 2) Component-based development improves code maintainability and team collaboration efficiency. 3) Responsive systems and virtual DOM improve rendering performance.

Vue.js vs. React: Ease of Use and Learning CurveVue.js vs. React: Ease of Use and Learning CurveMay 02, 2025 am 12:13 AM

Vue.js is easier to use and has a smooth learning curve, which is suitable for beginners; React has a steeper learning curve, but has strong flexibility, which is suitable for experienced developers. 1.Vue.js is easy to get started with through simple data binding and progressive design. 2.React requires understanding of virtual DOM and JSX, but provides higher flexibility and performance advantages.

See all articles

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft