How does reactivity function from a technical perspective?

Managing a simple store in my project has been a breeze (check out the code snippet). I've noticed that changes made to data in a RouterView reflect instantly in a Navigation Component. This behavior reminds me of an observer pattern, what do you think?

// store.js
import { reactive } from 'vue'

export const store = reactive({
    gender: "",
    name: "",
});

Question: Now I'm curious to learn more about how this mechanism operates and visualize how it would be implemented in Vanilla JS.

Answer №1

Based on the official documentation:

In Vue 3, Proxies are utilized for reactive objects while getter/setters are employed for refs.

The documentation also includes some pseudo-code snippets:

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, 'value')
      return value
    },
    set value(newValue) {
      value = newValue
      trigger(refObject, 'value')
    }
  }
  return refObject
}

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

By utilizing .focus() in iOS8, the virtual keyboard will be displayed and the page will automatically scroll upon touch

In the era before iOS8, when utilizing the Javascript .focus() method on an input element, it seemed as though nothing happened - the virtual keyboard did not make an appearance. However, with the latest iOS 8 update, executing the .focus() method initiall ...

Interactions between a service and a directive: interdependence or triggering of events

Issue: managing multiple directives that interact with a service or factory to communicate and log actions with a server. Should I establish dependencies between them? angular.module('someModule', []) .directive('someDir', ['l ...

Switching class names on click in Vue.js

When clicked, I would like to toggle the class name from "product fav" to "product fav active". The change should be conditional; if the class is already active, it should be removed. ...

How can we use THREE.js to make objects track other objects?

Currently, I am in the process of developing the PONG Game and I encountered an issue with making the computer play against the player. My goal is to have the computer follow the y-axis position of the ball, ensuring that both entities have distinct moveme ...

Enhancing Image Quality with jspdf and Html2Canvas

We are currently utilizing jsPDF and HTML2canvas to create PDFs, however, we have noticed that the image resolution is quite high. Is there a method available to obtain low-resolution images using jquery, javascript, jsPDF, and html2canvas? function addE ...

Tips for identifying and retrieving the checkbox and select box values in ASP.NET

I am trying to figure out how to detect the selected checkbox values and select box entries in my registration form. Here is the select: <p><label for="favorite">Favorite Player</label> <select name = "favor"> <o ...

Ensure the backslashes are removed from the AWS Lambda string API response

I have an AWS Lambda function where I am sending a string as my final response let abc= `"phone_exist":"0","calls":"0","lastaction":"0"` callback(null,abc); Output: "\"phone_exist\":\"0\",\"calls\":\"0\",\"l ...

Issue with md-stretch-tabs in Angular-Material causing a problem

I am in the process of developing an Angular-based application. ISSUE: I included md-stretch-tabs in my md-tabs element, but when I switch to tab#2, the tab retracts as if there is not enough space to flex. Is this problem related to dependencies or the c ...

What steps can be taken to prompt the layout to transition?

I have an element that sticks to the top based on the current scroll offset. The issue is that the layout doesn't update when there is space available after the stuck element. This creates a ghost gap where the stuck element used to be... http://fidd ...

When updating a form, it is essential to display select box data from the database effortlessly. It is also important to ensure that the select box data's id is

In my current project, a quasar (vuejs) app, I am faced with an issue related to an update form functionality. The challenge I am encountering is that when I submit the form without making any changes to the select box, it submits the label as a string ins ...

Is there a way to maintain a functioning associated watcher while resetting the value of a ref?

UPDATE: I managed to achieve the desired behavior in the MCV by making a change to resetArray: function resetArray() { // myArray.value = [] // old version myArray.value.length = 0 // new version } However, I am still puzzled as to why my MCV is not ...

Combining properties of JavaScript objects into one

Just starting my Vue journey and encountering a slight challenge. Displayed below is a table with various items: Whenever an item is selected and its quantity increased, I need my addOptional method (optional) to update a variable with the item's qu ...

Show the button's value inside a div when clicked using Javascript and HTML

I am troubleshooting an issue where the value of a button is not displayed in the picked_letters div when the button is clicked, despite having the appropriate code in both the html and javascript files. The structure of the html file is as follows: < ...

Promise retrying after failing in node.js

I am looking to implement a retry mechanism in my request using promises. Specifically, I want to initiate a refresh if I consistently receive a 401 error in a loop: (continue refreshing until a 200 status code is received). My initial attempt looked like ...

Exploring the Concept of Callbacks in JavaScript

What happens behind the scenes when a function is passed as a parameter in JavaScript and how does the engine recognize it as a callback? ...

What is the best method for transmitting data to the server using Ajax?

In order for the registration form to function properly, it must utilize Ajax to send data to the server. When the submit button is clicked, a spinning gear should appear. If the registration is successful, a message saying "You have successfully registe ...

subscriptions to behavior subjects may not function properly across all components

When setting up my global service, I instantiate a BehaviorSubject variable dataWorkflowService: export class CallWorkflowService { url = 'http://localhost:3000/'; selectedNode : BehaviorSubject<Node> = new BehaviorSubject(new Node(&a ...

Encountering Vue linting errors related to the defineEmits function

I am encountering an issue with the linting of my Vue SPA. I am using the defineEmits function from the script setup syntactic sugar (https://v3.vuejs.org/api/sfc-script-setup.html). The error messages are perplexing, and I am seeking assistance on how to ...

Utilizing Angular's DSCacheFactory in my Ionic App: A Guide

Can someone guide me on implementing DSCacheFactory in my Ionic/Cordova app? I am unsure about using this and its similarity to web cache. Your help in finding a solution is greatly appreciated. Thank you! ...

Issue with ng-pattern directive not working as expected within AngularJS

<label for="updateInterval" class="control-label" for="UpdateInterval">Choose Interval</label> <input name="intervalRange" id="intervalRange" ng-pattern="" type="number" class="form-control input-medium fld-updateinterval-val" placehold ...