What causes regular objects to become automatically reactive in Vue3?

There is an example discussed in this particular article. It mentions that a normal object is not 'reactive'.

Upon testing in this codesandbox environment, it was observed that changes made to the normal object, including a plain string, can automatically update the view.

<template>
  {{ personName }} <!-- will change to Amy, why? -->
  {{ person.name }} <!-- will change to Amy, why? -->
  {{ personRef.name }}
  {{ personReactive.name }}
  <button @click="changeName('Amy')">changeName</button>
</template>

<script setup>
import { ref, reactive } from "vue";

let personName = "John";
const person = { name: "John" };
const personRef = ref({ name: "John" });
const personReactive = reactive({ name: "John" });
const changeName = (name) => {
  personName = name;
  person.name = name;
  personRef.value.name = name;
  personReactive.name = name;
};
</script>

How is this behavior explained? Is there something missing in the Vue documentation?

An attempt was also made using the Vue SFC Playground, which yielded the same outcome.

Answer №1

When the normal variables do not become reactive, it's actually a result of a re-render triggered by the changeName() method. This re-render occurs because you modified the values of the reactive variables. Consequently, the DOM gets updated with the latest values correctly displayed for both normal and reactive variables.

To demonstrate this concept, I've prepared a forked version of your sandbox containing the following code:

<template>
  {{ personName }}
  {{ person.name }}
  {{ personRef.name }}
  {{ personReactive.name }}
  <button @click="changeReactiveName('Amy')">changeReactiveName</button>
  <button @click="changeNormalName('Fanoflix')">changeNormalName</button>
</template>

<script setup>
import { ref, reactive } from "vue";

let personName = "John";
const person = { name: "John" };
const personRef = ref({ name: "John" });
const personReactive = reactive({ name: "John" });

const changeReactiveName = (name) => {
  personRef.value.name = name;
  personReactive.name = name;
};

const changeNormalName = (name) => {
  personName = name;
  person.name = name;
};
</script>

Modifying only the non-reactive variables using changeNormalName() doesn't trigger a DOM re-render, so any changes won't be reflected in the DOM.

However, once you invoke the changeReactiveName() method, the DOM updates to reflect changes made to reactive variables. Thus, the updated values of non-reactive variables will also be rendered in the DOM showing Fanoflix.

For further insights, explore Vue's rendering mechanism in the documentation: docs

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

Discover the seamless transformation of a class definition into a Vue 3 component definition utilizing the dazzling 'tc39' decorators

The proposed API in the tc39/proposal-decorators repository is significantly different from the previous decorators API. Although TypeScript 5 doesn't fully support the new API yet, it's only a matter of time before the old API becomes deprecated ...

Copy both the image and JSON object to the clipboard

I am attempting to utilize the clipboard API to write an image and JSON object to the window clipboard. I am working with Vue and Electron and have successfully written an image and plain text, but I encounter an error when trying to write a JSON object: ...

Issues encountered with vue element checkbox functionality while in edit mode

I am currently utilizing checkboxes provided by Vue Element. You can take a look at them here: . However, I am encountering an issue where users are unable to select checkboxes in edit mode. Any assistance would be greatly appreciated. <el-checkbox-g ...

Having trouble getting Vue UI to install correctly on my new project using Laravel Framework version 8.83.7

I am having trouble installing Vue in my Laravel project. Here are the steps I follow: Run composer require laravel/ui Install Vue using: php artisan ui vue Install Vue with authentication using: php artisan ui vue --auth Then run: npm install ...

Vue - Error Message from Eslint Regarding Absence of Variable in Setup Function

Interestingly, the Vue.js documentation strongly recommends using the <script setup> syntax of the Composition API. The issue with this recommendation is that the documentation lacks depth and it conflicts with other tools (like eslint). Here is an e ...

Unable to manipulate or customize the V-slot component

I recently implemented the v-flip feature on my Nuxt webpage, resulting in the following template: <div class="about__cards"> <vue-flip class="about__single-card" active-click width = "350px" height="450px"> <template v-slot:front> ...

Troubleshooting Problem with QRCode Scanner in the Ionic Vue Framework with Capacitor

While working on my Vue.js project with Ionic and Capacitor, I encountered a challenge in reading QR Codes from the camera. Despite searching extensively, I couldn't find any specific solutions for Ionic Vue.js. However, I stumbled upon a small packag ...

Encountering CORS Error while trying to access Guest App in Virtualbox using Vue, Express, and Axios

I encountered an issue while trying to access my Vue app in Virtualbox from the host, both running on Linux Mint 20. Although I can now reach the login page from my host, I am consistently faced with a CORS error during login attempts: Cross-Origin Request ...

Compiling SCSS to CSS in Vue.js is a breeze

I am working on a vue js project that includes scss files. My goal is to compile these scss files into css and store them in the public folder. How can I achieve this? Should I make changes to the vue.config.js file? const path = require('path'); ...

Struggling to retrieve unpredictable data in a Vue.js component

Help! I'm trying to randomly display one of these names in my HTML, but I can't seem to make it work: Vue.component('modal', { template: '#modal-template', data: { items: [ { name: 'Elena' }, { na ...

Using Vue Testing Library with Nuxt.js: A Beginner's Guide

Looking to incorporate Vue Testing Library into my Nuxt.js project. Encountered an error right after installation, where running a test results in the following message: 'vue-cli-service' is not recognized as an internal or external command, op ...

Retrieve my information stored within a public transportation vehicle

Hello everyone, I am currently working on a Vue project and encountering a problem that I cannot seem to resolve. The issue at hand: I am trying to transfer data between components using a bus that I have defined in my main.js file. However, I am struggl ...

Encountering difficulties connecting to the database within Vue data tables

My php script was working fine with vuetify data, but now every page is showing the error message: Your search for "{{ search }}" found no results. It seems like this issue occurs when the script cannot fetch data from the database. Here is my d ...

I encountered a node error 'Error: write EPIPE' while building with vue-cli-service

I encountered a node error while using Jenkins to build the project. Error: write EPIPE at process.target._send (internal/child_process.js:841:20) at process.target.send (internal/child_process.js:712:19) at callback (/home/jenkins/agent/work ...

Strange Behavior in Vue Component - Loader Animation Fails to Display During Data Processing

I'm facing an issue where the loader for long data processing doesn't show up until after the processing is complete. I have a large object containing thousands of key-value items that I want to make filterable, which works but takes a few second ...

The resetFields() function fails to execute

While utilizing Vue3 with Element Plus to create a form, I encountered an issue with the resetFields() method not working as expected. The form is unable to automatically refresh itself. In the child component (Edit.vue): <template> <el-dialo ...

Tips for utilizing the /foo-:bar pathway in Nuxt.js?

I am trying to utilize the router /foo-:bar in Nuxt. Do you have any suggestions on how I could make this work? I attempted using pages/foo-_bar.vue but it did not yield the desired results. ...

Should the HTTP Accept-Language header be utilized to determine the user's locale?

I am utilizing Vue.js in combination with Laravel. I am looking to set the user's local language. Is this method recommended? axios.interceptors.request.use( function (config) { config.headers['Accept-Language']='en' o ...

Customize the asset path location in Webpack

I am currently working on a Vue application that utilizes Webpack for code minimization. Is there a method to dissect the chunks and adjust the base path from which webpack retrieves the assets? For example, by default webpack fetches assets from "/js" o ...

Struggling to locate images in Three.js

I'm facing a challenge with my Vue Cli app where I am attempting to use Three.js for rendering 3D objects within it. The issue arises when I attempt to load an image to utilize as a texture. let scene = new Three.Scene(); const spaceTexture = new Th ...