Issue with Vue.js variable not updating as expected

I'm struggling with a variable in vue.js.

Here's the situation - I want to set a loggedIn variable to true when a user logs in, and then set it to false when the user logs out. This is what my code looks like:

index.js:

export default {

  state: {
    loggedIn  : false
  },

  login() {
    var self = this;
    var creds = {
      username: 'username',
      password: 'password'
    }

    $.ajax({
      url: '/login',
      type: 'POST',
      data: creds,
      success: function(response) {
        self.state.loggedIn = true;
        alert('Logged in!!');
      },
      error: function() {
        alert('Error logging in!');
      }
    });
  },
}

App.vue:

import auth from './index.js';

module.exports = {

  data: function () {

    return {

      loggedIn: auth.state.loggedIn,
    }

  },

  watch: {
    loggedIn: function () {
      alert('loggedIn value has changed!!!');
    }
  },

}

In App.vue, you can see that my loggedIn variable relies on the imported value from index.js. However, it seems that loggedIn in App.vue isn't reacting to changes in loggedIn in index.js.

Any ideas on what might be causing this issue?

Thank you for your help!

Answer №1

If you want to have reactive data in your application, you need to assign it as the data of a component.

When you set a primitive value like auth.state.loggedIn to data.loggedIn, it simply creates a copy rather than establishing reactivity.

Therefore, even though changes to data.loggedIn will trigger reactivity, modifications to auth.state.loggedIn won't have the same effect since they are not directly linked.


The solution is to assign the entire state object to your component's data:

module.exports = {
  data () {
    return {
      auth: auth.state,
    }

  },

  watch: {
    'auth.loggedIn' () {
      alert('The value of loggedIn has been updated!!!');
    }
  }
};

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

What could be the issue with my JSON data stream?

Trying to set up the Fullcalendar JQuery plugin with a JSON feed has been a bit of a challenge. The example provided with the plugin works perfectly, so it seems like there might be an issue with my own feed. Here is the output from the working example JS ...

Discovering methods to access properties from another function

Can I access the value of variable w from another function? <script type="text/javascript"> var first = { myFirst: function(){ var w= 90; var q=12; }} var second= { mySecond: function(){ first.myFirst.w }} </script> ...

Issue with Bootstrap flash alert CSS on mobile devices is not functioning properly

I am in the process of developing a Rails application. Within my app, I utilize Bootstrap's CSS for displaying flash messages on alerts. Instead of fully incorporating Bootstrap's CSS, I only integrate styles related to alerts in order to prevent ...

Exporting a Component with React can be done in two ways: named exports and

There's a common syntax I've come across in various files: import React, {Component} from react; While I grasp the concept of named exports and default exports individually, I'm uncertain about how React manages this when exporting its cod ...

Using v-model within a nested v-for loop of a multi-level array

Hey there! I'm looking to create a dynamic table for managing employee meals based on the selected month. I've made some progress, but I'm encountering an issue where marking meals for one employee affects all other employees. It seems like ...

Exiting a void method in JavaScript/Typescript using the return or break statement

I find myself dealing with a complex method in Typescript that contains multiple if else if else constructs. It's a void method, and I'm wondering how I can exit the method based on a specific if condition without having to execute the remaining ...

Combining several mapGetters in a Vuex module with namespaced set to true: A guide

Exploring the combination of 2 mapGetters in one Case 1 One with namespaced: true, one without ...mapGetters('cart', ['quantity']), ...mapGetters({ isLoggedIn: 'isAuthenticated' }) Case 2 Both with namespaced: true ... ...

Attempting deletion with Node.js's Mongoose Framework

Having some trouble with the following code snippet. It doesn't seem to be functioning correctly and is resulting in a 404 error. Any insights on how to troubleshoot this issue? app.delete("/tm/v1/tasks", (req,res) => { Task.findOneAndDelete ...

Attempting to transmit information using Ajax to an object-oriented programming (OOP) class

Trying to send data with username, password, etc from an HTML form -> Ajax -> Instance -> OOP class file. Questioning the approach... Begins with the form on index.php <!-- Form for signing up --> <form method="post"> <div ...

Toggle class to a div upon clicking menu item

Seeking assistance with jQuery to develop a video player featuring a sub menu for displaying various content options upon selection. Here is a snapshot of the frontend design: view image Upon clicking on 'video' or 'audio', a distinct ...

How to customize the color of Navbar pills in Bootstrap 4 to fill the entire height

Is there a way to ensure that the background of nav-items is completely filled with color rather than just partially? I attempted to use Bootstrap pills, but it did not achieve the desired effect. I also experimented with my own CSS, but encountered simil ...

Troubleshooting: jQuery Drop event is not triggering

I am attempting to transfer links (.link) from one div (.folder) to another, but the drop event is not triggering. To make all .link divs droppable areas, I have disabled the default behavior in the dragenter and dragover events. Here is the code snippet: ...

Using Blob URL in localStorage after page reload with JavaScript

I am currently developing an application in Next.js without a server. I am utilizing an <input> tag to input a video file, which is then converted into a blob URL and saved in the local storage for use across sessions. However, after refreshing the ...

Differentiating between clicks and dragging interactions within an HTML 5 canvas

I am working on creating a basic map using the HTML 5 canvas. The idea is that dragging the mouse will move the map, and clicking will select the nearest waypoint. However, I have encountered an issue where I receive the click event even when dragging the ...

Retrieve the host name using the getStaticProps method

Can the hostname be accessed within the getStaticProps function? export async function getStaticProps(context) { // retrieving the hostname const hostname = ???? } ...

The issue of Storybook webpack failing to load SCSS files persists

I'm running into an issue where my styles are not loading in Storybook, even though I'm not getting any errors. Can someone help me out? My setup involves webpack 2.2.1. I've scoured Stack Overflow and GitHub for solutions, but nothing seem ...

Laravel Sanctum - Access Denied post login

My current project is a small web app developed using Laravel 8 sanctum and Vue. I have set up everything on both my local environment and the production server using Docker, ensuring consistency. The application is running smoothly on a subdomain called s ...

Combining CSS and JS files for accordion list - experiencing issues when used separately

Recently, I've been trying to create an accordion list and stumbled upon some code (HTML, CSS, and JS) on www.w3schools.com. When I have the code all in one document and run it as a single .html file, everything works perfectly. However, when I split ...

Optimal Timing for Stock Trading - Uncover the Ideal Days to Purchase and Vend Stocks

One possible solution I found was related to determining the maximum profit value. const pricesEachDay = [1,2,5,8,7,1,2,3] const mainFunction = (pricesEachDay) => { let buyPrice = pricesEachDay[0]; let bestProfit = 0; let startDay = 0; ...

The universal vue entity is not defined

Initially, I wanted to reuse my validator in another component, so I placed it in the myValidator.js file. I made sure to set the Vue object to window since I needed internationalization (i18n) in my myValidator.js. However, I encountered an error message ...