What is the reason behind the unexpected behavior of shallowReactive?

Recently, I started using vue3 and I am a bit confused about the concept of shallowReactive.

I have learned that only root-level properties are reactive for a shallow reactive object.

However, I noticed that even when I click the add button, the value of count2 still changes:

<script setup>
import { shallowReactive } from 'vue'

const test = shallowReactive({
  count1: 0,
  nested: {
    count2: 0
  }
})
const add = () => {
  test.count1++
  test.nested.count2++
}
</script>

<template>
  <button @click="add">+</button>
  <div>{{ test.count1 }}</div>
  <div>{{ test.nested.count2 }}</div>
</template>

Answer №1

Modifying something nested within a shallowReactive does not mean the mutation won't be executed. It simply indicates that Vue is not explicitly instructed to check for variances between the model (M) and the view/template/DOM (V) immediately.

When you alter test.count1 in the same function as well, which is being watched, the component undergoes a differential update. This process focuses on detecting disparities between the model and the view, disregarding whether the property is reactive or not. If discrepancies are found, they get updated accordingly.

To distinguish between changes in nested and non-nested properties, individual functions can be created. Notice that only the view updates when there is a change in the non-nested property. At this point, the entire template is scrutinized and adjusted based on the model:

const { createApp, shallowReactive } = Vue;

createApp({
  setup() {
    const test = shallowReactive({
      count1: 0,
      nested: {
        count2: 0
      }
    })
    const add = () => {
      test.count1++
    }
    const addWithoutUpdate = () => {
      test.nested.count2++;
    }
    return { test, add, addWithoutUpdate }
  }
}).mount('#app')
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.2.37/vue.global.prod.min.js"></script>
<div id="app">
  <button @click="add">+</button>
  <button @click="addWithoutUpdate">Only add to nested</button>
  <div>{{ test.count1 }}</div>
  <div>{{ test.nested.count2 }}</div>
</div>


In essence, shallowReactive lacks the ability to freeze nested objects. They remain mutable, yet Vue will only perform a diff on the template when a watched item truly alters. This could involve changes at the top level of the shallow reference or any other unrelated reactive variable.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using C# to send pictures to a WhatsApp contact

Is it possible to send an image along with a text message to a WhatsApp number through the API? https://api.whatsapp.com/send?phone=15551234567&text=I'm%20interested%20in%20your%20car%20for%20sale I have successfully sent text messages using thi ...

Issue with Angular 2 - Struggling with Routing

My objective is to create a menu with four links, each leading to a different HTML page: <p> <a routerLink="/function">Business Function</a> <a routerLink="/process">Business Process</a> <a routerLink="/appsystem"> ...

Upon refreshing, the user of the React JS application is redirected to a different page

My React JS app utilizes react-router-dom v6 to manage the routes. Everything was working fine until I integrated Firebase Firestore. Now, when I reload the seeker page, it redirects me to the home page instead of staying on the seeker page. This issue is ...

What is the best way to send the input text to the filter component in my React application?

I am currently working on developing an application utilizing the "Rick and Morty API" to display a list of characters with various attributes such as gender, alive status, images, etc. My main goal is to implement a search bar that allows users to search ...

Retrieve the processed data from a file using node.js

I have successfully read and parsed my file, however I am facing an issue with retrieving the output string. I want to access this string from a variable assigned to it on the client side. Despite using async series to handle callback functions effective ...

Unable to reach 'this' within a nested function

Struggling with a coding issue for hours now and in need of some assistance. The challenge at hand involves creating an object named Rank. Rank is expected to make DB calls in mongodb to retrieve data needed to populate a matrix, followed by executing nes ...

What causes the variation in `this` when viewing index.html in a browser versus supplying index.html through a node server?

My html file named index.html is referencing a javascript file <!DOCTYPE html> <html lang="en"> <head> <title>asd</title> <meta charset="utf-8"> </head> <body> <div id="app"></div> ...

What is the process for adjusting the input value dynamically in reactjs?

I am working on a dynamic time input row and I need to ensure that the values are updated correctly. This is the code snippet I am using: https://codesandbox.io/s/624vq8y7y3 When I run the code, the values in the TimeInput field do not change as expected ...

Retrieving the response data from a getJson request

I am currently working on implementing a function that will perform an action based on the response text received from a specific ajax call. However, I am struggling to access the response text field in my code. Here is the snippet: var response = $.getJS ...

Issue with fullcalendar.js: event times are not appearing on agenda view

I'm struggling to get timed events to display correctly on the agendaWeek view. The first two events, which are mine, show up as all day events instead of at their specified times. However, the last event from the documentation displays in the correct ...

What about nested elements with percentages, set positions, and fixed placements?

Picture: https://i.sstatic.net/KFNR1.png I am working on a design with a yellow container div that I want to keep at 50% width of the window. Inside this container is a purple image div that stretches to 100% of the parent container's width, and ther ...

Conceal a request URL within JavaScript through the use of Laravel/Ajax

I have an idea that I'm not sure is great or even feasible, but I really need to make it work. I am attempting to obfuscate a URL that needs to be used in a Javascript function as a parameter. This is what I currently have: <script> myFunction ...

Guide on acquiring the Tololtip Tail in your Menu's inventory

HTML <div id="MyForm"> <a> <img src="ImageMenu.png" /></a> <ul> <li> <a class="selected" href="#">One</a> </li> <li> <a href="#">Two& ...

What could be causing my console to display "NaN" when working with the class extension feature

During the development of my project, I encountered a problem with getting the parameter from the parent class. The value returned is NaN while the other one returns true. Here is the code snippet: class transportasi {//class parent constructor(nama ...

Unable to associate Slider values with TextFields in MaterialUI

Currently, I am trying to create a slide with 2 markers to indicate a price range and interact with it on the slide. Although I have linked the input with the slider, the connection from the slider to the input is not functioning properly. My attempt was t ...

Save the current time and date to a database by executing a mysql_query

<form action="actionMAppointment.php?stu_id=<?php echo $row_RecEdit['stu_id'] ?>" method="post"> Time: <input type = "time" name="appointmentTime" id = "appointmentTime" /> Date: <input type = ...

``Change the color of the sections in a 3D pie chart on a Highcharts

I am looking to create a custom pie chart with two different colors: one for the main surface and another for the sides. Currently, I can only configure the lighter blue color for the main surface, but I would like to also change the darker blue color for ...

What is the best way to recreate WordPress categories using static HTML pages?

As I consider converting my WordPress website to static HTML pages, I'm planning on editing them in tools like Responsive Site Designer, Dreamweaver, or SublimeText. My main concern is how I will organize content into categories without the convenien ...

Upon importing Chakra-UI in NextJS, the functionality may not work right away

Currently, I am diving into learning NextJS and Chakra-UI. Following the installation of Chakra-UI and attempting to import it, I encountered the error message shown below on the page. Any assistance in resolving this issue would be greatly appreciated. ...

Tips for removing a row from a table

I've been working on a responsive data table where each time I click an add button at the end of a row, a new row is added with the add button turning into a delete button. Below is the code I've implemented: The Table: <table id="invoice_ta ...