SoFunction
Updated on 2025-04-07

Detailed explanation of the specific usage of Vue Ref family bucket

1. ref

In Vue3,refBecome a family bucket, which can be used to reference DOM elements, component instances, and other objects in addition to creating responsive data. The following isrefSpecific usage:

1.1. Create responsive data

We can userefFunctions 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 userefFunction to create a responsive datacount, the initial value is0. We can useto access and modify this value.

1.2. Reference DOM elements

We can userefFunctions 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>})
&lt;/script&gt;
&lt;style scoped&gt;
&lt;/style&gt;

In this example, we userefFunction to create acontainerReferences, then use in the templateref="container"To bind this reference to a<div>on the element. existsetupIn the function, we useonMountedHook to access the value of this reference.

1.3. Reference component instances

We can userefFunctions 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 userefFunction to create achildReference, then bind this reference to a<Child>on component. existscriptIn, we expose this reference for use elsewhere.

1.4. Reference other objects

In addition to DOM elements and component instances, we can also userefFunctions to refer to other objects, for example:

&lt;template&gt;
  &lt;Child ref="child" /&gt;
&lt;/template&gt;
&lt;script setup lang="ts"&gt;
import { ref } from 'vue'
const data = { name: 'John' }
const obj = ref(data)
() // Output 'John' = 'Mary'
() // Output 'Mary'&lt;script&gt;
&lt;style scoped&gt;
&lt;/style&gt;

In this example, we userefFunction to refer to an objectdata, then assign this reference to aobjvariable. We can useTo access and modify this object. In this example, we willModified toMary, 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,refThe function first determines whether the value passed in is already arefobject, if so, it will be returned directly, otherwise a responsive object will be created asrefThe value of the object. ThenrefThe function will return a possessionvalueAn 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,isRefFunctions are used to determine whether an object isrefObject, it determines whether this object has a special attributeIS_REFTo make a judgment. The value of this special property istrue, means that this object is arefObject.

2.1. Use of isRef

&lt;template&gt;
  &lt;div class="wrapper"&gt;&lt;/div&gt;
&lt;/template&gt;
&lt;script setup lang="ts"&gt;
import { isRef, ref } from 'vue';
const name: string = 'Zhang San';
(isRef(name)); // false
const age = ref(10);
(isRef(age)); // true
&lt;/script&gt;
&lt;style scoped&gt;
&lt;/style&gt;

2.2. isRef source code

// Determine whether an object is a ref objectexport function isRef(r) {
  return Boolean(r &amp;&amp; r[ReactiveFlags.IS_REF])
}

3. shallowRef

In Vue3shallowRefFunction, used to create a "shallow" responsive object.

andrefThe difference between functions is,shallowRefFunctions do not convert their values ​​into responsive objects, but directly handle them as normal objects or arrays. This means that when modifiedshallowRefVue3 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 useshallowRefExample of function:

&lt;template&gt;
  &lt;div&gt;{{  }}&lt;/div&gt;
&lt;/template&gt;
&lt;script setup lang="ts"&gt;
import { shallowRef } from 'vue'
const obj = { name: 'John', age: 30 }
const ref = shallowRef(obj)
() // Output 'John' = 'Mary'
() // Output 'Mary'&lt;/script&gt;
&lt;style scoped&gt;
&lt;/style&gt;

In this example, we useshallowRefFunction to create a"Shallow"Responsive objectrefand set its value toobjObject. When we modifyWhen the value of the attribute,The value of the attribute has also changed. This is becauseobjObjects andrefObjects share the same reference.

3.2. ShallowRef source code

In Vue3,shallowRefThe 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]
}

shallowRefThe function will create aShallowRefImplobject, and take the passed in value as its internal_valueThe value of the attribute.ShallowRefImplThe object is agetandsetNormal object of method, when readvalueWhen attributes,getThe method will return_valueThe value of the attribute; when modifiedvalueWhen attributes,setThe method will assign the new value to_valueattribute and trigger corresponding dependencies.

Force update of DOM

4.1. Use of triggerRef

triggerRefIt is very simple to use, just pass oneRefThe 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 userefThe function creates a namedcountThe responsive reference of the original value is0. Then we need to manually update the count in some cases, and then we can usetriggerReffunction to trigger its update.

It should be noted that when usingtriggerRefWhen a function triggers an update, it will only updateRefThe object itself, without updating the components associated with it. Therefore, we should use it when we know that it is necessary to update manuallytriggerReffunction, and in normal casesVueIts own responsive system automatically updates related components.

4.2. Source code implementation of triggerRef

In Vue3,triggerRefFunction is used to trigger arefObject 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 isrefobject, if so, get its value and usetrackFunction tracking thisrefObject dependency. Then put thisrefAssign the value of the object to its ownvalueProperties and usetriggerThe function triggers thisrefObject dependency update. If the object passed in is notrefObject, a warning message will be output.

5. customRef

In Vue 3, acustomRefFunction to create a custom, responsive reference object. andrefandshallowRefThe difference is,customRefCan be customizedgetandsetThe implementation logic of the method can achieve more flexible and responsive behavior.

usecustomRefReference objects created by functions andrefThe object is similar, and also hasvalueAttribute, when reading this attribute, it will be triggeredgetExecution of the method; when modifying this property, it will be triggeredsetThe execution of the method and triggers the corresponding dependency update. andrefThe difference in the object is,customRefThe function itself does not process the incoming initial value, but instead directly acts asgetThe return value of the method needs to be processed manually by yourself.

Below iscustomRefExample of function usage:

5.1. Use customRef

import { customRef } from 'vue'
const myRef = customRef((track, trigger) =&gt; ({
  value: 0,
  get() {
    track()
    return 
  },
  set(newValue) {
     = newValue
    trigger()
  }
}))
() // Output 0 = 1
() // Output 1

In this example, usecustomRefThe function creates a custom reference objectmyRef, itsgetMethod is used to track dependencies, returnvaluevalue of the attribute;setMethods are used to modifyvalueThe value of the property and triggers the corresponding dependency update. When reading and modifyingmyRefThe object'svalueWhen the attribute is triggered, it will be triggered separatelygetandsetmethod.

Notice:customRefThe parameter of a function is a function, which receives two parameters, respectivelytrackandtriggerFunctions, 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, acustomRefFunction, 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_isRefattribute to identify it as arefobject; another name isvalueattributes for storing the value of the reference object and triggering the factory function when read and modifiedgetandsetmethod. existcustomRefThe last function returns thisrefObject.

Summary: This article introduces thereffunction,isReffunction,shallowRefFunctions andcustomReffunction.refFunctions are mainly used to create responsive objects, referencesDOMInstance, reference component instances, etc.isRefFunctions are mainly used to determine whether the incoming data is a responsive object.shallowRefThe 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.customRefFunctions can create custom reference objects, which can be customized.getandsetMethod implementation logic. In addition, the article also introducestriggerReffunction to triggerrefObject 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!