0

I'm just wondering how to create a global function wherein it checks whether the localStorage is not empty specifically if there's a token inside

What I've tried is creating a global variable in my main.js

Vue.$checkIfTokenIsNotEmpty = !!localStorage.getItem('token');
// this returns true or false

In my component,

<template>
    Is token Empty? {{ isTokenIsEmpty }} // I'm able to get true or false here
</template>

<script>
    export default {
        data(){
            return {
                 isTokenIsEmpty: this.$checkIfTokenIsNotEmpty
            }
        }    
    }
</script>

This works properly when I reload the page. The problem is, it's not reactive or real time. If I clear the localStorage, the value of my this.$checkIfTokenIsNotEmpty doesn't change. It only changes when I reload the page which is bad in my spa vue project.

jsonGPPD
  • 987
  • 4
  • 16
  • 31

2 Answers2

0

You can acces token like here: https://jsfiddle.net/djsj8dku/1/

  data: function() {
    return {
        world: 'world',
      get token() {
        return localStorage.getItem('token') || 0;
      },
      set token(value) {
        localStorage.setItem('token', value);
      }
    };
  }

Or you can use one of this packages: vue-reactive-storage, vue-local-storage

0

You cannot detect when localStorage is wiped out manually but you can watch when localStorage is updated. So watcher is what you need. Link

Regarding global function you can set a method & variable inside root component.

new Vue({
  el:"#app",
  data:{
     isTokenIsEmpty:null
  },
  methods: {
      checkIfTokenIsNotEmpty() {
         this.isTokenIsEmpty= !!localStorage.getItem('token');
      }
  }
})

Inside component,

mounted(){
  this.$root.checkIfTokenIsNotEmpty() //can be added anywhere when needed to check localStorage's Availablity
}

Html

<template> Is token Empty? {{ $root.isTokenIsEmpty }} // I'm able to get true or false here </template>
Helping hand
  • 2,800
  • 2
  • 19
  • 31