search
HomeWeb Front-endVue.jsHow to use shallowRef and shallowReactive in Vue3

How to use shallowRef and shallowReactive in Vue3

May 11, 2023 pm 11:07 PM
vue3shallowrefshallowreactive

shallowRef and shallowReactive

  • shallowRef functions only process basic type data.

  • shallowReactive function only processes the first layer of data.

  • Both need to be introduced when using them.

Did you still not understand what was said above? It doesn’t matter, just remember the above three items first, and then explain them in detail.

We talked about the ref function and the reactive function in the previous blog. Their function is to convert the data into responsive data. When the data is modified, the data can be displayed on the page in real time, and the basic data can also be displayed on the page in real time. Okay, no matter who you are, it’s all like this.

But there is a problem. When we change the data to responsive data, whether we use the ref function or the reactive function, they are both deep monitoring. What does that mean? It is the object wrapped by reactive. Even if there are 100 layers, that is, if you click on a hundred attributes in a row, you can still monitor the deepest data. In this case, there will be problems.

Problems with deep monitoring:

  • Both the ref function and the reactive function are deep monitoring.

  • If the amount of data is too large, it will consume super performance.

  • If we don’t need to deeply monitor the data, we can use the shallowRef function and shallowReactive function.

do you understand? It doesn’t matter if you don’t understand, we will know through a few cases.

Use shallowReactive non-depth monitoring

Remember that the shallowReactive function can only process the first layer of data.

Suppose our page has a personal information display, with name and age to be displayed. Our data is stored in the boy object, and age is under the news attribute of the boy object, that is, deep, but name is in Below the boy object, that is, on the first layer, we have two buttons to modify the name and age respectively to see what the effect will be.

<template>
  <div>
    <h2 id="姓名-name">姓名:{{name}}</h2>
    <h2 id="年龄-news-age">年龄:{{news.age}}</h2>
    <button @click="btn">修改name</button>
    <button @click="btn2">修改age</button>
  </div>
</template>

<script>
import { shallowReactive, toRefs } from "vue";
export default {
  name: "App",
  setup() {
    const boy = shallowReactive({
      name: "我是????????.",
      news: {
        birthday: "2012-10-14",
        age: 10
      }
    });

    const btn = () => {
      boy.name = "????????.";
    };

    const btn2 = () => {
      boy.news.age++;
    };

    return { ...toRefs(boy), btn, btn2 };
  }
};
</script>

Let’s click two buttons respectively to see the page changes.

How to use shallowRef and shallowReactive in Vue3

Through the effects, let’s summarize a little bit:

  • shallowReactive will only wrap the first layer of data

  • By default it can only listen to the first layer of data.

  • If you want to change the data of multiple layers, you must first change the data of the first layer, and then change the data of other layers. Only then will the data on the view change.

Use shallowRef for non-depth monitoring

As mentioned at the beginning, the shallowRef function can only process basic type data, why? Because The shallowRef function monitors .value changes. It is not a change in the first layer of data. So if you want to change the data created by shallowRef, you should xxx.value = XXX.

Look at the code:

<template>
  <div>
    <h2 id="姓名-boy">姓名:{{boy}}</h2>
    <button @click="btn">修改boy</button>
  </div>
</template>

<script>
import { shallowRef } from "vue";
export default {
  name: "App",
  setup() {
    const boy = shallowRef("我是????????.");

    const btn = () => {
      boy.value = "????????.";
    };

    return { boy, btn };
  }
};
</script>

Click the button to modify the value of boy.

How to use shallowRef and shallowReactive in Vue3

As you can see from the screenshot above, the data can be modified normally.

Then a question remains: shallowRef function only processes basic type data?

Look at the following case:

<template>
  <div>
    <h2 id="姓名-boy-name">姓名:{{boy.name}}</h2>
    <h2 id="年龄-boy-news-age">年龄:{{boy.news.age}}</h2>
    <button @click="btn">修改name</button>
    <button @click="btn2">修改age</button>
  </div>
</template>

<script>
import { shallowRef } from "vue";
export default {
  name: "App",
  setup() {
    const boy = shallowRef({
      name: "我是????????.",
      news: {
        birthday: "2012-10-14",
        age: 10
      }
    });

    const btn = () => {
      boy.value.name = "????????.";
    };

    const btn2 = () => {
      boy.value.news.age++;
    };

    return { boy, btn, btn2 };
  }
};
</script>

In this code, we wrap an object with shallowRef, then display the name and age on the page, and then we modify the name and age through the button , take a look at the effect of the page.

How to use shallowRef and shallowReactive in Vue3

So, the shallowRef function can only handle basic type data.

The above is the detailed content of How to use shallowRef and shallowReactive in Vue3. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Vue.js vs. React: A Comparative Analysis of JavaScript FrameworksVue.js vs. React: A Comparative Analysis of JavaScript FrameworksApr 30, 2025 am 12:10 AM

Vue.js and React each have their own advantages and disadvantages. When choosing, you need to comprehensively consider team skills, project size and performance requirements. 1) Vue.js is suitable for fast development and small projects, with a low learning curve, but deep nested objects can cause performance problems. 2) React is suitable for large and complex applications, with a rich ecosystem, but frequent updates may lead to performance bottlenecks.

Vue.js vs. React: Use Cases and ApplicationsVue.js vs. React: Use Cases and ApplicationsApr 29, 2025 am 12:36 AM

Vue.js is suitable for small to medium-sized projects, while React is suitable for large projects and complex application scenarios. 1) Vue.js is easy to use and is suitable for rapid prototyping and small applications. 2) React has more advantages in handling complex state management and performance optimization, and is suitable for large projects.

Vue.js vs. React: Comparing Performance and EfficiencyVue.js vs. React: Comparing Performance and EfficiencyApr 28, 2025 am 12:12 AM

Vue.js and React each have their own advantages: Vue.js is suitable for small applications and rapid development, while React is suitable for large applications and complex state management. 1.Vue.js realizes automatic update through a responsive system, suitable for small applications. 2.React uses virtual DOM and diff algorithms, which are suitable for large and complex applications. When selecting a framework, you need to consider project requirements and team technology stack.

Vue.js vs. React: Community, Ecosystem, and SupportVue.js vs. React: Community, Ecosystem, and SupportApr 27, 2025 am 12:24 AM

Vue.js and React each have their own advantages, and the choice should be based on project requirements and team technology stack. 1. Vue.js is community-friendly, providing rich learning resources, and the ecosystem includes official tools such as VueRouter, which are supported by the official team and the community. 2. The React community is biased towards enterprise applications, with a strong ecosystem, and supports provided by Facebook and its community, and has frequent updates.

React and Netflix: Exploring the RelationshipReact and Netflix: Exploring the RelationshipApr 26, 2025 am 12:11 AM

Netflix uses React to enhance user experience. 1) React's componentized features help Netflix split complex UI into manageable modules. 2) Virtual DOM optimizes UI updates and improves performance. 3) Combining Redux and GraphQL, Netflix efficiently manages application status and data flow.

Vue.js vs. Backend Frameworks: Clarifying the DistinctionVue.js vs. Backend Frameworks: Clarifying the DistinctionApr 25, 2025 am 12:05 AM

Vue.js is a front-end framework, and the back-end framework is used to handle server-side logic. 1) Vue.js focuses on building user interfaces and simplifies development through componentized and responsive data binding. 2) Back-end frameworks such as Express and Django handle HTTP requests, database operations and business logic, and run on the server.

Vue.js and the Frontend Stack: Understanding the ConnectionsVue.js and the Frontend Stack: Understanding the ConnectionsApr 24, 2025 am 12:19 AM

Vue.js is closely integrated with the front-end technology stack to improve development efficiency and user experience. 1) Construction tools: Integrate with Webpack and Rollup to achieve modular development. 2) State management: Integrate with Vuex to manage complex application status. 3) Routing: Integrate with VueRouter to realize single-page application routing. 4) CSS preprocessor: supports Sass and Less to improve style development efficiency.

Netflix: Exploring the Use of React (or Other Frameworks)Netflix: Exploring the Use of React (or Other Frameworks)Apr 23, 2025 am 12:02 AM

Netflix chose React to build its user interface because React's component design and virtual DOM mechanism can efficiently handle complex interfaces and frequent updates. 1) Component-based design allows Netflix to break down the interface into manageable widgets, improving development efficiency and code maintainability. 2) The virtual DOM mechanism ensures the smoothness and high performance of the Netflix user interface by minimizing DOM operations.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor