Validate the existence of a token in the browser's localStorage

-1

the question that I have a token saved in the localstorage and what I want is that if that browser token is deleted I automatically redirect to the login window if the need to refresh the window or something else, imagine that I made a manually deleting that token then immediately take me to the login window. I'm using Node.js, vue and vuex, I was reading that the localstorage is not reactive in return but I did not understand much what it said.

    
asked by Jonathan Gregorio Rodriguez To 04.12.2018 в 01:45
source

2 answers

2

Hi, you can use computed properties

Vue({
 computed: {
   token() {
    return storage.get('TOKEN_KEY');
   }
 }
});

And with this you could do it "reactive", you can consult the following link for more information: computed properties

If what you need to be in your entire application, you can use mixins to record the behavior in all the components of your application.

Vue.mixin({
  computed: {
    token() {
     return storage.get('TOKEN_KEY');
    } 
  } 
})

And to do what you need then you would have to add watchers.

    
answered by 04.12.2018 в 02:36
0
export default {
  props: ['user'],
  data() {
    return {
      items: [
        { header: 'Today' },
        { avatar: 'https://vuetifyjs.com/static/doc-images/lists/1.jpg', title: 'Brunch this weekend?', subtitle: "<span class='text--primary'>Ali Connors</span> &mdash; I'll be in your neighborhood doing errands this weekend. Do you want to hang out?" },
        { divider: true, inset: true },
        { avatar: 'https://vuetifyjs.com/static/doc-images/lists/2.jpg', title: 'Summer BBQ <span class="grey--text text--lighten-1">4</span>', subtitle: "<span class='text--primary'>to Alex, Scott, Jennifer</span> &mdash; Wish I could come, but I'm out of town this weekend." },
      ],
      vertoken: '',
    };
  },
  watch() {
    // this.vertoken = localStorage.getItem('accessToken');
    // this.debouncedGetrouter();
    this.verificartoken();
  },
  created() {
    this.verificartoken();
  },
  methods: {
    verificartoken() {
      if (localStorage.getItem('accessToken') === undefined || localStorage.getItem('accessToken') === null) {
        this.$router.push({ name: 'Login', params: { successAlert: true } });
      }
    },
    token() {
      return localStorage.getItem('accessToken');
    },
    token2() {
      if (!this.token()) {
        this.$router.push({ name: 'Login', params: { successAlert: true } });
      }
    },
  },
  components: {
    payroll: PayRoll,
    Expenses,
    Incomes,
    UserChart,
  },
};
</script>

This is how I have my code but there is no reaction when I delete the variable manually from the localstorage.

    
answered by 08.12.2018 в 08:23