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

Durandal attempts to retrieve a view located within the viewmodel directory

Having an issue with durandal's compose binding as it is looking for views under app/viewmodels instead of app/views The ViewModel code: define(["fields/fieldClosures"], function (fields) { var ctor = function(opt) { this.value = opt.valu ...

Create an Interactive Data Visualization with JSON using CanvasJS Charts

Having some trouble creating a chart using CanvasJS. After fetching data from the API and checking the JSON array, I encounter two errors when attempting to generate dataPoints for the graph: "data invalid" on the data field and "NaN" on the value field. ...

The some() method in Javascript with an extra argument

I want to validate if at least one element in an array satisfies a certain condition. The condition is based on a variable. Here's an example of how I'm currently attempting this: function checkCondition(previousValue, index, array) { retur ...

Using Unicode JSON in Laravel blade to pass data to React components, encountering an issue with JSON parsing

I currently have a JSON object stored in the database: { "ui": {}, "title": "Hola mundo 2", "values": {}, "properties": {}, "description": "descripcion" } Within the Laravel controller, ...

Eliminating unnecessary CSS from the codebase of a website

Currently, I am making adjustments to a website template that I downloaded for free online. I have noticed that even if I delete a div from the code, the corresponding CSS styles remain in one or more files. Is there any tool available that can automatic ...

The Minimax algorithm experiencing issues in Next.js

I recently wrote some code in Next.js, but unfortunately, it's not functioning as expected. Despite my best efforts and attempts at utilizing alpha beta pruning, the code still fails to work properly. The issue lies in the fact that it simply returns ...

Is it possible to update labels on an AngularJS slider using a timeout function?

I recently started implementing an AngularJS slider to navigate through various date and time points. Specifically, I am utilizing the draggable range feature demonstrated in this example - https://jsfiddle.net/ValentinH/954eve2L/ The backend provides the ...

What is the process of performing numerical calculations using jQuery?

I need to deduct certain input values from the total price. Here's the code snippet: $('.calculate-resterend').click(function(e) { e.preventDefault(); var contant = $('.checkout-contant').val(); var pin = $('.che ...

Having trouble getting the video to load on your Mozilla Firefox browser?

Unable to play video on Firefox. Error message: URL.createObjectURL(video): Error decoding media resource blob: NS_ERROR_DOM_MEDIA_FATAL_ERR (0x806e0005) Details: Decoder may not support the requested video format with YUV444 chroma subsampling. Tried usi ...

Oops! RangeError [MESSAGE_CONTENT_TYPE]: The content of the message must be a string that contains at least one character

Can someone help me troubleshoot my regular send command? I keep encountering an error message even after following suggestions from previous answers. Here is the error: RangeError [MESSAGE_CONTENT_TYPE]: Message content must be a non-empty string. at ...

How can I retrieve the Sequelize results in the form of a 2D array rather than an array of objects?

I have a situation where I am using the Sequelize query() method like this: const sequelize = new Sequelize(...); ... // IMPORTANT: Cannot modify this query const queryFromUser = "SELECT table1.colname, table2.colname FROM table1 JOIN table2 ON/*...*/ ...

Persisted state in Vuex using createPersistedState is experiencing some issues with partial persistence

After studying the persisted-state documentation at https://www.npmjs.com/package/vuex-persistedstate, I am attempting to only partially persist the state by implementing the following code: export default new Vuex.Store({ state: { user: {}, sign ...

The Controller received a JSON object that was empty

I know this question has been asked countless times, but I've tried all solutions with no success. Here's the JSON object in question: { "manufacture":"HP", "model":"testModel", "serialNumber":"testSerial", "description":"Test Descript ...

Problem encountered while revalidating Next.js and Sanity documents through a webhook

I'm currently developing a Next.js 13 project that utilizes Sanity as its CMS and is deployed on Vercel. To ensure that components and pages are revalidated whenever a new testimonial is added, updated, or removed in Sanity, I have configured a webhoo ...

The form response values consistently show as undefined, attempting to send them to the backend with no success so far after trying two different approaches

I've tried approaching this issue in two different ways, but both times I end up with a value of "undefined" instead of the user input from the form. Just to give some context, I'm using material UI forms for this project. The first approach inv ...

Challenges related to using the require() method in JavaScript

I've been encountering an issue while trying to run the JavaScript client for the Tumblr API from their Github repository. The error message I keep getting is "require not defined" which has led me on a hunt across various forums and websites, includi ...

The change handler of the TS RadioGroup component, instead of returning an array of possible strings, returns a unique

My interface declaration for StopData is shown below: export interface StopData { stopName: string, stopType: 'stop' | 'waypoint' } I have implemented a radio group to choose the 'stopType', which consists of two radi ...

What steps can be taken to ensure that an ObjectID does not transition into a primitive form

Is there a way to avoid an ObjectID from being converted into a primitive data type when transferring in and out of Redis? Would converting it to a JSON string be a possible solution? Thanks! ...

Leverage D3 force simulation as a functional programming tool

Currently, I am utilizing d3-force for collision detection in my project: function customLayout(nodesWithCoordinates) { const simulation = forceSimulation(nodesWithCoordinates) .force('collide', forceCollide(4.5)) .stop() .tick(300 ...

Switching left navigation in material-ui when the user interacts within the application boundary

I am currently implementing a toggle feature in my AppBar to display the LeftNav. I have successfully set it up to close when the toggle is clicked again. However, I wish to mimic the behavior of most left nav bars where clicking anywhere outside of the ...