[Vuejs]-Create Global Function For Checking If LocalStorage is not empty โ€“ Vue.JS

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>

Leave a comment