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.
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>
{{person.name}} -{{person.age}}-{{person.job.web}}-{{person.job.trade}}
<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>
{{name}}-{{age}}-{{web}}-{{trade}}
<button @click="handleChangeAttrs">修改属性</button>
<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>
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>
{{person}} {{name}}-{{age}}-{{web}}-{{trade}} <button @click="handleChangeAttrs">修改属性</button>
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>
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()
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!

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

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)

Hot Topics











Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses <router-link to="/" component window.history.back(), and the method selection depends on the scene.

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

There are three ways to refer to JS files in Vue.js: directly specify the path using the <script> tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values for each element; and the .map method can convert array elements into new arrays.
