2

After login i set inside store and inside localStorage the variable "authenticated" = true.

How can i check in each page if authenticated==true and show different menu element?

(i'm using ssr)

Thanks

2 Answers 2

6
  1. Set Vuex state authenticated at the point of login.
  2. Be sure to clear that when you logging user out or app is starting and you are checking e.g. if JWT is still valid.
  3. Set computed variable in components requiring that state. computed() { authenticated () => { return this.$store.state.authenticated } }

  4. Use it in your template with <v-if>.

Good luck!

Sign up to request clarification or add additional context in comments.

Comments

3

If you do not want to use Vuex,

  1. Set the initial state { authenticated: false } with vue-persistent-state.
  2. Use this.authenticated as you would in a vanilla Vue app.

Example:

import persistentStorage from 'vue-persistent-storage';

const initialState = {
  authenticated: false
};
Vue.use(persistentStorage, initialState);

Vue.component('my-login', {
  methods: {
    login: function () {
      doLogin()  // call to auth API
        .then(() => { this.authenticated = true })
        .catch(() => { this.authenticated = false })
    }
  }
})

new Vue({
  el: '#app',
  created: function () {
    if (loginIsValid) {  // check auth validity upon app bootup
      this.authenticated = true
    } else {
      this.authenticated = false
    }
  }
})

Now authenticated is available as data in all components and Vue instances. Any changes to this.authenticated will be stored in localStorage, and you can use this.authenticated as you would in a vanilla Vue app.

If you want to understand how this works, the code is pretty simple. It basically

  1. adds a mixin to make initialState available in all Vue instances, and
  2. watches for changes and stores them.

Disclaimer: I'm the author of vue-persistent-state.

Comments

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.