Table of Contents
reactive()
Basic usage
Responsive proxy vs original object
In Vue, the status is deep responsive by default of. But in some scenarios, we may want to create a
Although reactive() is powerful, it also has the following limitations:
Vue provides a
ref 的解包
ref 在模板中的解包
ref 在响应式对象中的解包
ref 在数组和集合类型的解包
toRef()
toRefs()
响应式原理
Vue2 的限制
Vue3 的响应式系统
Home Web Front-end Vue.js Comprehensive inventory of ref and reactive in vue3

Comprehensive inventory of ref and reactive in vue3

Mar 02, 2023 pm 07:40 PM
front end vue.js

I know if you have such doubts when using Vue3, "ref and rective can create a responsive object, how should I choose?", "Why does a responsive object lose its responsiveness after destructuring? How should it be handled? ?” Today we will take a comprehensive inventory of ref and reactive. I believe you will gain something different after reading it. Let’s learn together!

Comprehensive inventory of ref and reactive in vue3

reactive()

Basic usage

We can use it in Vue3 reactive() Create a responsive object or array:

import { reactive } from 'vue'

const state = reactive({ count: 0 })
Copy after login

This responsive object is actually a Proxy, Vue will use this Proxy Side effects are collected when the properties are accessed, and side effects are triggered when the properties are modified.

To use responsive state in component templates, you need to define and return it in the setup() function. [Related recommendations: vuejs video tutorial, web front-end development]

<script>
import { reactive } from &#39;vue&#39;

export default {  setup() {    const state = reactive({ count: 0 })    return {      state    }  }}
</script>

<template>
  <div>{{ state.count }}</div>
</template>
Copy after login

Of course, you can also use <script setup>,## Top-level imports and variable declarations in #<script setup> can be used directly in templates.

<script setup>
import { reactive } from &#39;vue&#39;

const state = reactive({ count: 0 })


Copy after login

Responsive proxy vs original object

reactive() returns a Proxy of the original object, they Are not equal:

const raw = {}
const proxy = reactive(raw)

console.log(proxy === raw) // false
Copy after login

The original object can also be used in the template, but modifying the original object will not trigger an update. Therefore, to use Vue's reactive system, you must use proxies.

<script setup>
const state = { count: 0 }
function add() {
  state.count++
}
</script>

<template>
  <button @click="add">
    {{ state.count }} <!-- 当点击button时,始终显示为 0 -->
  </button>
</template>
Copy after login

To ensure the consistency of access to the proxy, calling

reactive() on the same original object will always return the same proxy object, while calling ## on an existing proxy object #reactive() will return itself: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>const raw = {} const proxy1 = reactive(raw) const proxy2 = reactive(raw) console.log(proxy1 === proxy2) // true console.log(reactive(proxy1) === proxy1) // true</pre><div class="contentsignin">Copy after login</div></div>This rule also applies to nested objects. Relying on deep responsiveness, nested objects within responsive objects are still proxies:

const raw = {}
const proxy = reactive({ nested: raw })
const nested = reactive(raw)

console.log(proxy.nested === nested) // true
Copy after login

shallowReactive()

In Vue, the status is deep responsive by default of. But in some scenarios, we may want to create a

shallow reactive object

to make it responsive only at the top level. In this case, we can use shallowReactive(). <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>const state = shallowReactive({ foo: 1, nested: { bar: 2 } }) // 状态自身的属性是响应式的 state.foo++ // 下层嵌套对象不是响应式的,不会按期望工作 state.nested.bar++</pre><div class="contentsignin">Copy after login</div></div>Note: Shallow reactive objects should only be used for root-level state in components. Avoid nesting it in a deeply reactive object, as the properties inside it will have inconsistent responsive behavior and will be difficult to understand and debug after nesting.

Limitations of reactive()

Although reactive() is powerful, it also has the following limitations:

    Only Valid for object types (objects, arrays, and collection types such as
  • Map

    , Set), and for string, number, and boolean Such primitive types are invalid.

  • Because Vue's reactive system is tracked through property access, if we directly "replace" a reactive object, this will cause the reactive connection to the original reference to be lost:
  • <script setup>
    import { reactive } from &#39;vue&#39;
    
    let state = reactive({ count: 0 })
    function change() {  // 非响应式替换
     state = reactive({ count: 1 })}
    </script>
    
    <template>
     <button @click="change">
       {{ state }} <!-- 当点击button时,始终显示为 { "count": 0 } -->
     </button>
    </template>
    Copy after login

  • When assigning or destructuring the properties of a reactive object to local variables, or passing the property into a function, responsiveness will be lost:
  • const state = reactive({ count: 0 })
    
    // n 是一个局部变量,和 state.count 失去响应性连接
    let n = state.count
    // 不会影响 state
    n++
    
    // count 也和 state.count 失去了响应性连接
    let { count } = state
    // 不会影响 state
    count++
    
    // 参数 count 同样和 state.count 失去了响应性连接
    function callSomeFunction(count) {
     // 不会影响 state
     count++
    }
    callSomeFunction(state.count)
    Copy after login

  • In order to solve the above limitations,
ref

shines on the scene!

ref()

Vue provides a

ref()

method that allows us to create reactive refs using any value type.

Basic usage

ref()

Pack the incoming parameters into a ref object with value attributes : <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>import { ref } from &amp;#39;vue&amp;#39; const count = ref(0) console.log(count) // { value: 0 } count.value++ console.log(count.value) // 1</pre><div class="contentsignin">Copy after login</div></div>Similar to the properties of responsive objects, the

value

properties of ref are also responsive. At the same time, when the value is of object type, Vue will automatically use reactive() to process the value. A ref containing an object can reactively replace the entire object:

<script setup>
import { ref } from &#39;vue&#39;

let state = ref({ count: 0 })
function change() {
  // 这是响应式替换
  state.value = ref({ count: 1 })
}
</script>

<template>
  <button @click="change">
    {{ state }} <!-- 当点击button时,显示为 { "count": 1 } -->
  </button>
</template>
Copy after login

ref No loss of responsiveness when deconstructing properties from a general object or passing properties to a function:

Reference

Detailed answers to front-end advanced interview questions

ref()

allows us to create ref objects using any value type without losing them Pass these objects responsively. This feature is very important and is often used to extract logic into Combined functions. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>// mouse.js export function useMouse() { const x = ref(0) const y = ref(0) // ... return { x, y } }</pre><div class="contentsignin">Copy after login</div></div><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>&lt;script setup&gt; import { useMouse } from &amp;#39;./mouse.js&amp;#39; // 可以解构而不会失去响应性 const { x, y } = useMouse() &lt;/script&gt;</pre><div class="contentsignin">Copy after login</div></div><h3 id="strong-ref-的解包-strong"><strong>ref 的解包</strong></h3><p>所谓解包就是获取到 ref 对象上 <code>value 属性的值。常用的两种方法就是 .valueunref()unref() 是 Vue 提供的方法,如果参数是 ref ,则返回 value 属性的值,否则返回参数本身。

ref 在模板中的解包

当 ref 在模板中作为顶层属性被访问时,它们会被自动解包,不需要使用 .value 。下面是之前的例子,使用 ref() 代替:

<script setup>
import { ref } from &#39;vue&#39;

const count = ref(0)
</script>

<template>
  <div>
    {{ count }} <!-- 无需 .value -->
  </div>
</template>
Copy after login

还有一种情况,如果文本插值({{ }})计算的最终值是 ref ,也会被自动解包。下面的非顶层属性会被正确渲染出来。

<script setup>
import { ref } from &#39;vue&#39;

const object = { foo: ref(1) }

</script>

<template>
  <div>
    {{ object.foo }} <!-- 无需 .value -->
  </div>
</template>
Copy after login

其他情况则不会被自动解包,如:object.foo 不是顶层属性,文本插值({{ }})计算的最终值也不是 ref:

const object = { foo: ref(1) }
Copy after login

下面的内容将不会像预期的那样工作:

<div>{{ object.foo + 1 }}</div>
Copy after login

渲染的结果会是 [object Object]1,因为 object.foo 是一个 ref 对象。我们可以通过将 foo 改成顶层属性来解决这个问题:

const object = { foo: ref(1) }
const { foo } = object
Copy after login
<div>{{ foo + 1 }}</div>
Copy after login

现在结果就可以正确地渲染出来了。

ref 在响应式对象中的解包

当一个 ref 被嵌套在一个响应式对象中,作为属性被访问或更改时,它会自动解包,因此会表现得和一般的属性一样:

const count = ref(0)
const state = reactive({ count })

console.log(state.count) // 0

state.count = 1
console.log(state.count) // 1
Copy after login

只有当嵌套在一个深层响应式对象内时,才会发生解包。当 ref 作为 浅层响应式对象 的属性被访问时则不会解包:

const count = ref(0)
const state = shallowReactive({ count })

console.log(state.count) // { value: 0 } 而不是 0
Copy after login

如果将一个新的 ref 赋值给一个已经关联 ref 的属性,那么它会替换掉旧的 ref:

const count = ref(1)
const state = reactive({ count })

const otherCount = ref(2)
state.count = otherCount

console.log(state.count) // 2
// 此时 count 已经和 state.count 失去连接
console.log(count.value) // 1
Copy after login

ref 在数组和集合类型的解包

跟响应式对象不同,当 ref 作为响应式数组或像 Map 这种原生集合类型的元素被访问时,不会进行解包。

const books = reactive([ref(&#39;Vue 3 Guide&#39;)])
// 这里需要 .value
console.log(books[0].value)

const map = reactive(new Map([[&#39;count&#39;, ref(0)]]))
// 这里需要 .value
console.log(map.get(&#39;count&#39;).value)
Copy after login

toRef()

toRef 是基于响应式对象上的一个属性,创建一个对应的 ref 的方法。这样创建的 ref 与其源属性保持同步:改变源属性的值将更新 ref 的值,反之亦然。

const state = reactive({
  foo: 1,
  bar: 2
})

const fooRef = toRef(state, &#39;foo&#39;)

// 更改源属性会更新该 ref
state.foo++
console.log(fooRef.value) // 2

// 更改该 ref 也会更新源属性
fooRef.value++
console.log(state.foo) // 3
Copy after login

toRef() 在你想把一个 prop 的 ref 传递给一个组合式函数时会很有用:

<script setup>
import { toRef } from &#39;vue&#39;

const props = defineProps(/* ... */)

// 将 `props.foo` 转换为 ref,然后传入一个组合式函数
useSomeFeature(toRef(props, &#39;foo&#39;))
</script>
Copy after login

toRef 与组件 props 结合使用时,关于禁止对 props 做出更改的限制依然有效。如果将新的值传递给 ref 等效于尝试直接更改 props,这是不允许的。在这种场景下,你可以考虑使用带有 getsetcomputed 替代。

注意:即使源属性当前不存在,toRef() 也会返回一个可用的 ref。这让它在处理可选 props 的时候非常有用,相比之下 toRefs 就不会为可选 props 创建对应的 refs 。下面我们就来了解一下 toRefs

toRefs()

toRefs() 是将一个响应式对象上的所有属性都转为 ref ,然后再将这些 ref 组合为一个普通对象的方法。这个普通对象的每个属性和源对象的属性保持同步。

const state = reactive({
  foo: 1,
  bar: 2
})

// 相当于
// const stateAsRefs = {
//   foo: toRef(state, &#39;foo&#39;),
//   bar: toRef(state, &#39;bar&#39;)
// }
const stateAsRefs = toRefs(state)

state.foo++
console.log(stateAsRefs.foo.value) // 2

stateAsRefs.foo.value++
console.log(state.foo) // 3
Copy after login

从组合式函数中返回响应式对象时,toRefs 相当有用。它可以使我们解构返回的对象时,不失去响应性:

// feature.js
export function useFeature() {
  const state = reactive({
    foo: 1,
    bar: 2
  })

  // ...
  // 返回时将属性都转为 ref
  return toRefs(state)
}
Copy after login
<script setup>
import { useFeature } from &#39;./feature.js&#39;
// 可以解构而不会失去响应性
const { foo, bar } = useFeature()
</script>
Copy after login

toRefs 只会为源对象上已存在的属性创建 ref。如果要为还不存在的属性创建 ref,就要用到上面提到的 toRef

以上就是 ref、reactive 的详细用法,不知道你有没有新的收获。接下来,我们来探讨一下响应式原理。

响应式原理

Vue2 的限制

大家都知道 Vue2 中的响应式是采⽤ Object.defineProperty() , 通过 getter / setter 进行属性的拦截。这种方式对旧版本浏览器的支持更加友好,但它有众多缺点:

  • 初始化时只会对已存在的对象属性进行响应式处理。也是说新增或删除属性,Vue 是监听不到的。必须使用特殊的 API 处理。

  • 数组是通过覆盖原型对象上的7个⽅法进行实现。如果通过下标去修改数据,Vue 同样是无法感知的。也要使用特殊的 API 处理。

  • 无法处理像 MapSet 这样的集合类型。

  • 带有响应式状态的逻辑不方便复用。

Vue3 的响应式系统

针对上述情况,Vue3 的响应式系统横空出世了!Vue3 使用了 Proxy 来创建响应式对象,仅将 getter / setter 用于 ref ,完美的解决了上述几条限制。下面的代码可以说明它们是如何工作的:

function reactive(obj) {
  return new Proxy(obj, {
    get(target, key) {
      track(target, key)
      return target[key]
    },
    set(target, key, value) {
      target[key] = value
      trigger(target, key)
    }
  })
}

function ref(value) {
  const refObject = {
    get value() {
      track(refObject, &#39;value&#39;)
      return value
    },
    set value(newValue) {
      value = newValue
      trigger(refObject, &#39;value&#39;)
    }
  }
  return refObject
}
Copy after login

不难看出,当将一个响应性对象的属性解构为一个局部变量时,响应性就会“断开连接”。因为对局部变量的访问不会触发 get / set 代理捕获。

我们回到响应式原理。在 track() 内部,我们会检查当前是否有正在运行的副作用。如果有,就会查找到存储了所有追踪了该属性的订阅者的 Set,然后将当前这个副作用作为新订阅者添加到该 Set 中。

// activeEffect 会在一个副作用就要运行之前被设置
let activeEffect

function track(target, key) {
  if (activeEffect) {
    const effects = getSubscribersForProperty(target, key)
    effects.add(activeEffect)
  }
}
Copy after login

副作用订阅将被存储在一个全局的 WeakMap<target, Map<key, Set<effect>>> 数据结构中。如果在第一次追踪时没有找到对相应属性订阅的副作用集合,它将会在这里新建。这就是 getSubscribersForProperty() 函数所做的事。

trigger() 之中,我们会再次查找到该属性的所有订阅副作用。这一次我们全部执行它们:

function trigger(target, key) {
  const effects = getSubscribersForProperty(target, key)
  effects.forEach((effect) => effect())
}
Copy after login

这些副作用就是用来执行 diff 算法,从而更新页面的。

这就是响应式系统的大致原理,Vue3 还做了编译器的优化,diff 算法的优化等等。不得不佩服尤大大,把 Vue 的响应式系统又提升了一个台阶!

(学习视频分享:vuejs入门教程编程基础视频

The above is the detailed content of Comprehensive inventory of ref and reactive in vue3. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Vue: a perfect pairing of front-end development tools PHP and Vue: a perfect pairing of front-end development tools Mar 16, 2024 pm 12:09 PM

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

Questions frequently asked by front-end interviewers Questions frequently asked by front-end interviewers Mar 19, 2024 pm 02:24 PM

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

How to use Go language for front-end development? How to use Go language for front-end development? Jun 10, 2023 pm 05:00 PM

With the development of Internet technology, front-end development has become increasingly important. Especially the popularity of mobile devices requires front-end development technology that is efficient, stable, safe and easy to maintain. As a rapidly developing programming language, Go language has been used by more and more developers. So, is it feasible to use Go language for front-end development? Next, this article will explain in detail how to use Go language for front-end development. Let’s first take a look at why Go language is used for front-end development. Many people think that Go language is a

C# development experience sharing: front-end and back-end collaborative development skills C# development experience sharing: front-end and back-end collaborative development skills Nov 23, 2023 am 10:13 AM

As a C# developer, our development work usually includes front-end and back-end development. As technology develops and the complexity of projects increases, the collaborative development of front-end and back-end has become more and more important and complex. This article will share some front-end and back-end collaborative development techniques to help C# developers complete development work more efficiently. After determining the interface specifications, collaborative development of the front-end and back-end is inseparable from the interaction of API interfaces. To ensure the smooth progress of front-end and back-end collaborative development, the most important thing is to define good interface specifications. Interface specification involves the name of the interface

Is Django front-end or back-end? check it out! Is Django front-end or back-end? check it out! Jan 19, 2024 am 08:37 AM

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

Exploring Go language front-end technology: a new vision for front-end development Exploring Go language front-end technology: a new vision for front-end development Mar 28, 2024 pm 01:06 PM

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Can golang be used as front-end? Can golang be used as front-end? Jun 06, 2023 am 09:19 AM

Golang can be used as a front-end. Golang is a very versatile programming language that can be used to develop different types of applications, including front-end applications. By using Golang to write the front-end, you can get rid of a series of problems caused by languages ​​​​such as JavaScript. For example, problems such as poor type safety, low performance, and difficult to maintain code.

How to implement instant messaging on the front end How to implement instant messaging on the front end Oct 09, 2023 pm 02:47 PM

Methods for implementing instant messaging include WebSocket, Long Polling, Server-Sent Events, WebRTC, etc. Detailed introduction: 1. WebSocket, which can establish a persistent connection between the client and the server to achieve real-time two-way communication. The front end can use the WebSocket API to create a WebSocket connection and achieve instant messaging by sending and receiving messages; 2. Long Polling, a technology that simulates real-time communication, etc.

See all articles