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.
ref Value
Syntax: const Variable name =
toRef(source object, a property under the source object)
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: '前端开发', trade: '互联网' } }); </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: '前端开发', trade: '互联网' } }); 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: '前端开发', trade: '互联网' } }); 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: '前端开发', trade: '互联网' } }); // 想要修改指定哪个对象具备响应式,那么就使用toRef函数处理,toRef(源对象,源对象下的某个属性) const name = toRef(person,'name'); const age = toRef(person,'age'); // 经过了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
toRef() function
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: '前端开发', trade: '互联网' } }); // 使用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 object
ref()What is received is a pure value
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.
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)
toRefs()shown
<script setup> import { reactive,toRefs } from "vue"; const person = reactive({ name:"川川", age: 18, job: { web: '前端开发', trade: '互联网' } }); // 通过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
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
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!

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

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

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


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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

SublimeText3 English version
Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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
A free and powerful IDE editor launched by Microsoft
