Reactivity in Vue not responding when listening from a different object

Can someone help me understand why my Vue object is not reactive to changes in another object? See the code snippet below.

exampleObject = {
    exampleProperty: null
}

exampleObject.update = function () {
    this.exampleProperty = 'updated data'
}

exampleVue = new Vue({ data: exampleObject.exampleProperty })
                   
console.log(exampleVue.data) // Outputs: null

exampleObject.update()

console.log(exampleVue.data) // Still outputs: null... Shouldn't it be displaying 'updated data'?

I'd appreciate any insights on where I might have gone wrong with this implementation. Thanks!

Answer №1

If you're looking to create a reactive object in Vue, you have a couple of options. In Vue 2, you can use observable, while in Vue 3, you can utilize reactive. This allows you to create objects that react to changes automatically. For instance, the code snippet below showcases how to create a data store with a reactive state object:

import { observable } from 'vue'

const test_vue = {
  state: observable({
    test: null
  }),
  setTest() {
    this.state.test = 'data'
  }
}

test_vue.setTest() // => state.test === 'data'

Check out this demo for Vue 2 or this demo for Vue 3 to see it in action.

Answer №2

Make sure to define the test value as a property and use the set function as a method in Vue.js:

test = {
  test: null
}

test.set = function() {

  this.test = 'data'

}

test_vue = new Vue({
  data() {
    return {
      test: test.test
    }
  },
  methods: {
    set: test.set
  }
})


console.log(test_vue.test)

test_vue.set()

console.log(test_vue.test)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

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

Ensuring the node array is easily accessible within the view

I am currently working on building a simple messaging system using express/nodejs. Although I have successfully implemented the feature to send messages to all users, I now want to enable users to have private 1-to-1 conversations. My aim is straightforwa ...

JavaScript class syntax allows for the definition of inherited instance fields

In the code snippet below, I have implemented a way to define a prototype with a simple property that can be inherited by objects using the prototype: const SCXMLState = Object.setPrototypeOf( Object.defineProperties({ addChild() { } isStat ...

The act of receiving becomes ineffective when it was intended to be functional - Nextjs/JavaScript

When using nextjs, I encountered an issue while trying to map my array to getstaticpaths for generating getstaticprops. Every time I attempted to map the result, I received an error stating 'mycatagoriesis not a function'. Below is a snippet fro ...

EJS forEach method not displaying output

Trying to work with this .ejs file that's supposed to loop through an object and retrieve data from an API. However, after fetching the data, it appears that nothing is being displayed on the screen. I've checked the API results in the console l ...

Angular code is malfunctioning and not delivering the expected results

I currently have setup the code below: var videoControllers = angular.module('videoControllers', []); videoControllers.videoControllers('VideoDetailController', function($scope, $routeParams, $http){ $http.get('http://localho ...

Navigate back to the previous page without reloading

Initially, I must clarify that the title of my query may not be entirely representative of what I wish to convey. The situation at hand is as follows: I have developed a jQuery table designed for exhibiting video records. Embedded within this table is a hy ...

What is the reason the useEffect hook does not function properly with a state variable within context?

Check out my code here. I'm trying to display the content of the array testingData, but it's not showing up. If I remove the useEffect hook, it works fine. Can you help me understand why and how to fix it? ...

Increase the date and time by a specified number of days

After searching for solutions on how to add a specific number of days to a given date, I came across various methods. However, my requirement is to add days to both Date and Time in the format MM-DD-YYYY HH:MM:SS. I attempted a method which worked fine wh ...

Currently seeking user coordinates for Vue implementation

I recently started using Vue and I'm working on capturing the lat/long of a user to be used in other functions within Vue. Currently, I am retrieving the coordinates and plan to utilize them in an API but for now, I am just logging them. Although I c ...

Component cannot be shown on the screen

<template> <div v-for="corpus in getCorpora" v-bind:key="corpus.id"> <Corpus v-bind="corpus" /> </div> </template> <script> import Corpus from "../components/Corpus"; impor ...

What is the process of embedding base64 encoded data into an image in Javascript after retrieving the data from Azure Blob Storage?

I am attempting to insert an image by utilizing the base64 data pattern, rather than a URL link. Initially, I retrieve the data from Azure Blob storage using the Azure Node.js SDK: Azure Node.js SDK After downloading the data as a string, I am unsure of ...

Transforming Adobe Animate CC into a customized Vue.js component

Can someone share the optimal method for integrating published Adobe Animate CC HTML5 canvas / JS files into a Vue.js component? Appreciate it ...

Saving similar and dissimilar information in a database

I have been working on implementing a Like and Unlike feature for users to interact with products. Following this tutorial at , I've completed the necessary steps. However, I'm facing an issue where the likes are not being stored in the database ...

Text located in the bottom right corner of the window with the use of JavaScript

Is there a way to replace text at the bottom right of the window, as opposed to the page, so that it remains fixed in the corner of the window? I'm looking to create a "share" link that is always visible. ...

In what way can data be retrieved from within a useEffect block externally?

Essentially, I'm facing an issue with retrieving data from the DateView component in my ChooseCalendar component. The code that retrieves this data is located within a useEffect block due to passing a dateType variable as part of a useState to the com ...

The production build of Angular 2 with special effects amplification

I am currently working on an Angular 2 Beta 8 app that I need to bundle and minify for production deployment. Despite configuring the system to generate a Single File eXecutable (SFX) bundle, I am encountering issues with creating a minified version of the ...

Using setState in an external function: A step-by-step guide

import Request from 'superagent'; const fetchApi = () => { let apiUrl = '/* URL */'; return Request.get(apiUrl).then((response) => { this.setState({ data: response.body }); }); } export d ...

Exploring JSON data in AngularJS

After creating a new Angular App, I decided to store some data in a JSON file. My main concerns are where to best store the .json file within the app and how to access it. Currently, I am facing this error in my Chrome console: GET http://localhost:8000/t ...

Implementing a 10-second alert display in selenium

Task at Hand: I need to display the alert on my page for a few seconds to allow reading. Is there any function in Selenium Web-driver that can help with this? I am new to automation and have been learning about explicit waits. I tried using explicit wait ...

What could be causing this error to appear: Unable to locate the file './components/forms/LoginForm'

What could be causing the error message to appear when I run the npm run dev command? npm run development ERROR in ./resources/js/app.js 5:0-53 Module not found: Error: Can't resolve './components/forms/LoginForm' in 'D:\wamp64&bs ...