Implementing automatic updates for Vue.js model data from a global object

I'm new to working with Vuejs and I'm encountering an issue with updating data from a global object automatically. My project involves the use of ES6 and Vuejs.

The problem I'm facing is related to enabling/disabling a button based on a global object's property. When I change the 'disabled' option in the global object to false, the button doesn't become enabled as expected.

You can view a simple example in this fiddle: https://fiddle.jshell.net/daer/nsk95tez/

Even though the 'disabled' state is changed to false when clicking "Change state", the Button remains disabled.

<div id="some">
  <p>Current state: {{disabled}}</p>
  <button type="button" v-bind:disabled="disabled">Button</button>
</div>
<br>
<button id="state" type="button" v-on:click="changeState">Change state</button>

class stateList {
    constructor() {
        this.disabled = true;
    }
};
// export default (new stateList);


// import state from '../state/';
var state = new stateList;

var some = new Vue({
  el: '#some',
  data: {
    disabled: state.disabled
  },
  methods: {
    methodOne: function(e) {
      // ...
    }
  }
});

var changeState = new Vue({
  el: '#state',
  methods: {
    changeState: function(e) {
      state.disabled = false;
      alert(state.disabled);
    }
  }
});

Answer №1

The issue lies in the fact that you are not actually updating the variable data.disabled, hence the button state remains unchanged. What you are doing is creating a data object and a state object, and simply copying one value data.disabled=state.disabled between them upon creation of the Vue instance (you are not passing a reference to the variable, but rather just the variable itself). To resolve this, you need to set the state object as the data object.

el: '#some',
data: state,
methods: {

https://fiddle.jshell.net/nsk95tez/2/

However, using an ES6 class to store state is unnecessary. A key feature of Vue.js is that the data variable is a simple object. An ES6 class is essentially syntactic sugar for creating objects with inheritance, which is not needed in this scenario.

Instead, try the following:

var state = {disable:true};

https://fiddle.jshell.net/nsk95tez/1/ Here is the updated js fiddle example.

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

The MongoDB GridFS is refusing to accept the buffer being written

Hey everyone, I've been working on this issue for nearly a day now and can't seem to figure it out. I'm utilizing multer's inMemory flag to upload an image from my website. My approach involves writing the buffer received from multer to ...

Managing Events in Angular 2 and Creating Custom Event Handlers

Currently, I am in the process of developing a component library in Angular 2 for our app teams to utilize. One of the components I recently created is a modal, but I am encountering some accessibility challenges. Specifically, I want the modal to close wh ...

Styling text in JavaScript and CSS with colored fonts and underlines

I am looking to customize the CSS for the font style. <div id="a" onmouseover="chbg('red','b')" onmouseout="chbg('white','b')">This will change b element</div> <div id="b">This is element b</div ...

Arrange an asynchronous function in Node.js

I have been attempting to set up a schedule for an asynchronous function (with async/await return type) to run every two minutes. Although I have tried using the generic setInterval, as well as various node modules such as node-schedule, cron, node-cron, ...

How to monitor and respond to HTML modifications in a child component from a parent component in Angular framework

In the setup I have, there is a main component known as @Component({ selector: 'parent-comp' template: '<child-comp [inputData]="responseData"></child-comp> }) export class ChildComponent { public responseData: any; ...

Handle errors originating from unsuccessful connections to a server named "Event" when using RxJS's fromEvent method

Using rxjs fromEvent to establish a connection with a named sse Event, I am looking to handle an Error in case of connection loss namedEvent() { try { const eventSource = new EventSource( 'adress' ); return fromEvent ...

How to play audio with a source path that includes the special character "%" in JavaScript

Having an issue with playing an audio file that has '%' in its name. I've tried using the tag <audio src="test%320.mp3" controls></audio>, but it seems like the file is not being found when I try to play it. Can anyone ...

Is there a way to retrieve the current object as a JSON string from inside the object using either jquery or javascript?

Looking for a way to return the current instance as a JSON text so that the values can be sent via an ajax request to a server-side script. Uncertain about where to apply the "this" keyword in a jQuery selector function Actor(){ this.input=function(pnam ...

The method WebKitBrowser.StringByEvaluatingJavaScriptFromString does not provide any output

After running all JavaScript, I need to retrieve the HTML content. However, I am facing an issue using WebKit.NET where the method WebKitBrowser.StringByEvaluatingJavaScriptFromString does not return anything, even with a simple alert(). When I try passi ...

Is it possible to customize the close icons on the autocomplete feature in Material UI?

Is there a solution to change the icon while keeping its function when clicked? I am looking to replace this Icon <Autocomplete multiple id="checkboxes-tags-demo" options={top100Films} disableCloseOnSelect getOpt ...

Need assistance with jQuery AJAX?

Hey there, I'm a new member and I've gone through the different Ajax Help topics but still can't figure out why my code isn't working. Here's what I have: $(document).ready(function(){ $.ajax({ type: "GET", ur ...

"Is it possible for the package-lock.json file to not update when a package is removed from the

When I add a package manually to my package.json file and run npm install, the dependencies of that new package are updated in my package-lock.json. However, if I then delete that package from package.json and run npm install, the dependencies of that pac ...

Send user a notification upon detecting changes in the database - using JavaScript and AJAX!

Hey there! I'm diving into the world of JavaScript and AJAX for the first time, and I could really use some guidance on a particular issue. I'm looking to implement a feature where the user is notified whenever there is a change in a value of a ...

The alignment of two elements is off in mobile display

Why aren't my two divs centered in mobile view? I am using Vuetify CSS flex helper justify-center to try and achieve it, but it doesn't seem to be working. Even when I use justify-sm-center, it still doesn't work. What am I missing? <v-co ...

Update data in PHP dynamically without reloading the page

It would be great if they are doing well! I have encountered a minor issue - everything seems to work perfectly, but it doesn't quite meet my requirements. I am referring to this particular function: <script> var previous = null; var current = ...

What are the steps for integrating Angularfire2 into an Angular application?

Trying to integrate Angularfire2 into a fresh Angular project, but encountered an issue while following the official documentation. This is the guide I followed Upon reaching step 7 - Inject AngularFirestore, console errors were displayed: If anyone has ...

Eliminate the ArrayOfObjects by filtering out the items with a specific ID

Here is an array of objects I've named mycart[]: [{"id":"6","quantity":"20","price":1500,"title":"casual blue strip"}, {"id":"10","quantity":"2","price":1500,"title":"casual blue round neck"},{"id":"5","quantity":20,"price":150,"title":"casual ...

What is the best way to instantly update $scope when working with non-angular code?

Working with a non-angular library requires establishing communication between them. <div id="MoipWidget" data-token="{{personaltoken}}" callback-method-success="successCB" callback-method-error="errorCB"></div> Upon page load, a token must b ...

Relocate the bxslider carousel to the specific div clicked on

Is it possible to move the slider to the selected div when using bxslider? I have a carousel below. Currently, when you click on the controls (left/right arrows), it only moves one slide/div at a time, keeping the active div always on the left side. Howev ...

Angular Promises - Going from the triumph to the disappointment callback?

It seems like I might be pushing the boundaries of what Promises were intended for, but nonetheless, here is what I am attempting to do: $http.get('/api/endpoint/PlanA.json').then( function success( response ) { if ( response.data.is ...