0

I am having trouble a variable in vue.js.

Scenario - when a user logs in, I want to set a loggedIn variable to true and set it to false when the user logs out. My code:

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!!!');
    }
  },

}

As you can see, in App.vue, my loggedIn variable depends on what's imported from index.js. However, it doesn't appear that loggedIn in App.vue is reactive to loggedIn in index.js.

Does anyone know what I might be doing wrong?

Thanks in advance!

1 Answer 1

1

In order to make some data reactive, you must set it as the data of a component.

Since auth.state.loggedIn holds a primitive (a Boolean), assigning its value to data.loggedIn simply copies it over to data.loggedIn.

So while data.loggedIn is reactive, auth.state.loggedIn is not. The two are simply never linked up.


The only way to make this work is to assign the whole state object to your data:

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

  },

  watch: {
    'auth.loggedIn' () {
      alert('loggedIn value has changed!!!');
    }
  }
};
Sign up to request clarification or add additional context in comments.

1 Comment

PERFECT! Bless your soul!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.