1. ref
In Vue3,ref
Become a family bucket, which can be used to reference DOM elements, component instances, and other objects in addition to creating responsive data. The following isref
Specific usage:
1.1. Create responsive data
We can useref
Functions to create responsive data, for example:
<template> <div>{{ count }}</div> </template> <script setup lang="ts"> import { ref } from 'vue' const count = ref(0) () // Output 0 += 1 () // Output 1</script> <style scoped> </style>
Note that after being wrapped by ref, you need .value to assign
In this example, we useref
Function to create a responsive datacount
, the initial value is0
. We can useto access and modify this value.
1.2. Reference DOM elements
We can useref
Functions to reference DOM elements, for example:
<template> <div ref="container"></div> </template> <script setup lang="ts"> import { ref, onMounted } from 'vue' const container = ref(null) // Note: The variable name here must be consistent with the attribute name on the labelonMounted(() => { () // Output <div></div>}) </script> <style scoped> </style>
In this example, we useref
Function to create acontainer
References, then use in the templateref="container"
To bind this reference to a<div>
on the element. existsetup
In the function, we useonMounted
Hook to access the value of this reference.
1.3. Reference component instances
We can useref
Functions to reference component instances, for example:
<template> <Child ref="child" /> </template> <script setup lang="ts"> import { ref } from 'vue' import Child from './' const child = ref(null) </script> <style scoped> </style>
In this example, we useref
Function to create achild
Reference, then bind this reference to a<Child>
on component. existscript
In, we expose this reference for use elsewhere.
1.4. Reference other objects
In addition to DOM elements and component instances, we can also useref
Functions to refer to other objects, for example:
<template> <Child ref="child" /> </template> <script setup lang="ts"> import { ref } from 'vue' const data = { name: 'John' } const obj = ref(data) () // Output 'John' = 'Mary' () // Output 'Mary'<script> <style scoped> </style>
In this example, we useref
Function to refer to an objectdata
, then assign this reference to aobj
variable. We can useTo access and modify this object. In this example, we will
Modified to
Mary
, and then foundAlso modified.
1.5. ref source code
In Vue3, the source code of the ref function is as follows:
import { isObject } from '@vue/shared' import { ReactiveFlags, reactive } from './reactive' export function ref(value) { // If the value is already a ref object, return it directly if (isRef(value)) { return value } // Create a responsive object let valueIsObject = isObject(value) const ref = { // Mark this object as a ref object [ReactiveFlags.IS_REF]: true, // Get the value of ref get value() { // If value is an object, a responsive object is returned if (valueIsObject) { return reactive(value) } return value }, // Set the value of ref set value(newVal) { if (valueIsObject) { value = newVal valueIsObject = isObject(newVal) return } // If value is a primitive value, modify it directly value = newVal } } return ref }
In this source code,ref
The function first determines whether the value passed in is already aref
object, if so, it will be returned directly, otherwise a responsive object will be created asref
The value of the object. Thenref
The function will return a possessionvalue
An object of an attribute. When reading this attribute, if its value is an object, it will return a responsive object, otherwise it will directly return its value; when modifying this attribute, if its value is an object, the new value will be converted into a responsive object, otherwise its value will be directly modified.
2. isRef
In Vue3,isRef
Functions are used to determine whether an object isref
Object, it determines whether this object has a special attributeIS_REF
To make a judgment. The value of this special property istrue
, means that this object is aref
Object.
2.1. Use of isRef
<template> <div class="wrapper"></div> </template> <script setup lang="ts"> import { isRef, ref } from 'vue'; const name: string = 'Zhang San'; (isRef(name)); // false const age = ref(10); (isRef(age)); // true </script> <style scoped> </style>
2.2. isRef source code
// Determine whether an object is a ref objectexport function isRef(r) { return Boolean(r && r[ReactiveFlags.IS_REF]) }
3. shallowRef
In Vue3shallowRef
Function, used to create a "shallow" responsive object.
andref
The difference between functions is,shallowRef
Functions do not convert their values into responsive objects, but directly handle them as normal objects or arrays. This means that when modifiedshallowRef
Vue3 will not track these changes when an object's attributes or elements of an array. This "shallow" responsive object is very useful for scenarios where no fully responsiveness is required, such as caching some data or tracking certain states.
3.1. Use of shallowRef
Here is a useshallowRef
Example of function:
<template> <div>{{ }}</div> </template> <script setup lang="ts"> import { shallowRef } from 'vue' const obj = { name: 'John', age: 30 } const ref = shallowRef(obj) () // Output 'John' = 'Mary' () // Output 'Mary'</script> <style scoped> </style>
In this example, we useshallowRef
Function to create a"Shallow"
Responsive objectref
and set its value toobj
Object. When we modifyWhen the value of the attribute,
The value of the attribute has also changed. This is because
obj
Objects andref
Objects share the same reference.
3.2. ShallowRef source code
In Vue3,shallowRef
The source code of the function is as follows:
import { isObject, toRawType } from '@vue/shared' import { track, trigger } from './effect' import { ReactiveFlags } from './reactive' const shallowGet = (value) => value const shallowSet = () => { ( `Value assigned to a shallow ref ${String(value)} is not reactive, ` + `expecting explicitly passing deep: true in ref() options` ) } class ShallowRefImpl { public readonly __v_isRef = true public readonly [ReactiveFlags.IS_SHALLOW] = true constructor(public _value) {} get value() { track(this, 'get', 'value') return this._value } set value(newValue) { if (newValue !== this._value) { this._value = newValue trigger(this, 'set', 'value', newValue) } } } export function shallowRef(value) { return new ShallowRefImpl(value) } export function isShallowRef(value) { return !!value[ReactiveFlags.IS_SHALLOW] }
shallowRef
The function will create aShallowRefImpl
object, and take the passed in value as its internal_value
The value of the attribute.ShallowRefImpl
The object is aget
andset
Normal object of method, when readvalue
When attributes,get
The method will return_value
The value of the attribute; when modifiedvalue
When attributes,set
The method will assign the new value to_value
attribute and trigger corresponding dependencies.
Force update of DOM
4.1. Use of triggerRef
triggerRef
It is very simple to use, just pass oneRef
The object is just used as a parameter. For example:
import { ref, triggerRef } from 'vue' const count = ref(0) // In some cases, you need to manually update the count, you can use triggerReftriggerRef(count)
In this example, we useref
The function creates a namedcount
The responsive reference of the original value is0
. Then we need to manually update the count in some cases, and then we can usetriggerRef
function to trigger its update.
It should be noted that when usingtriggerRef
When a function triggers an update, it will only updateRef
The object itself, without updating the components associated with it. Therefore, we should use it when we know that it is necessary to update manuallytriggerRef
function, and in normal casesVue
Its own responsive system automatically updates related components.
4.2. Source code implementation of triggerRef
In Vue3,triggerRef
Function is used to trigger aref
Object dependency update. The source code is as follows:
import { effect } from './effect' import { track, trigger } from './operations' export function triggerRef(ref) { if (ref.__v_isRef) { const value = if (isTracking()) { track(ref, 'set', 'value') } = value trigger(ref, 'set', 'value', value) } else { (`triggerRef() expects a ref object passed as its argument.`) } }
In this source code, first determine whether the incoming object isref
object, if so, get its value and usetrack
Function tracking thisref
Object dependency. Then put thisref
Assign the value of the object to its ownvalue
Properties and usetrigger
The function triggers thisref
Object dependency update. If the object passed in is notref
Object, a warning message will be output.
5. customRef
In Vue 3, acustomRef
Function to create a custom, responsive reference object. andref
andshallowRef
The difference is,customRef
Can be customizedget
andset
The implementation logic of the method can achieve more flexible and responsive behavior.
usecustomRef
Reference objects created by functions andref
The object is similar, and also hasvalue
Attribute, when reading this attribute, it will be triggeredget
Execution of the method; when modifying this property, it will be triggeredset
The execution of the method and triggers the corresponding dependency update. andref
The difference in the object is,customRef
The function itself does not process the incoming initial value, but instead directly acts asget
The return value of the method needs to be processed manually by yourself.
Below iscustomRef
Example of function usage:
5.1. Use customRef
import { customRef } from 'vue' const myRef = customRef((track, trigger) => ({ value: 0, get() { track() return }, set(newValue) { = newValue trigger() } })) () // Output 0 = 1 () // Output 1
In this example, usecustomRef
The function creates a custom reference objectmyRef
, itsget
Method is used to track dependencies, returnvalue
value of the attribute;set
Methods are used to modifyvalue
The value of the property and triggers the corresponding dependency update. When reading and modifyingmyRef
The object'svalue
When the attribute is triggered, it will be triggered separatelyget
andset
method.
Notice:customRef
The parameter of a function is a function, which receives two parameters, respectivelytrack
andtrigger
Functions, they are used to track dependencies and trigger dependency updates.
5.2. Source code of customRef function
import { track, trigger } from './effect' export function customRef(factory) { const ref = { __v_isRef: true, get value() { return factory().get() }, set value(newValue) { factory().set(newValue) } } return ref } export function triggerRef(ref) { trigger(ref, 'set', 'value', ) }
In this source code, acustomRef
Function, which takes a factory function as a parameter, is used to create a custom reference object. Inside the function, a normal object is createdref
, it has a read-only__v_isRef
attribute to identify it as aref
object; another name isvalue
attributes for storing the value of the reference object and triggering the factory function when read and modifiedget
andset
method. existcustomRef
The last function returns thisref
Object.
Summary: This article introduces theref
function,isRef
function,shallowRef
Functions andcustomRef
function.ref
Functions are mainly used to create responsive objects, referencesDOM
Instance, reference component instances, etc.isRef
Functions are mainly used to determine whether the incoming data is a responsive object.shallowRef
The function creates a "shallow" responsive object that only tracks the changes in the attributes of the value, but not the changes in the attributes inside the object.customRef
Functions can create custom reference objects, which can be customized.get
andset
Method implementation logic. In addition, the article also introducestriggerRef
function to triggerref
Object dependency update.
This is the end of this article about the detailed usage of Vue Ref family bucket. For more related Vue Ref content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!