Skip to content Skip to sidebar Skip to footer

Using Vuejs Plugin On The Main.js File

Im trying to create a plugin for manage the Oauth2 token data in my vuejs app. I created the plugin following some few tutorials that are available on the internet. but when a try

Solution 1:

You are adding $authStorage to the prototype of Vue.

Vue.prototype.$authStorage = authStorage

That means will only be available on instances of the Vue object (ie. the result of new Vue(...).

If you want $authStorage to be available as a property of Vue without creating an instance, you need to add it as a static property.

Vue.$authStorage = authStorage

But, if it were me, I would probably take a different approach. I would likely build the AuthStorage plugin like this:

const authStorage = {
    getToken() {
      let token = localStorage.getItem('access_token')
      let expiration = localStorage.getItem('expiration')
      if (!token || !expiration) {
        returnnull
      }
      if (Date.now() > parseInt(expiration)) {
        this.destroyToken()
        returnnull
      }

      return token
    },
    setToken(accessToken, expiration, refreshToken) {
      localStorage.setItem('access_token', accessToken)
      localStorage.setItem('expiration', expiration + Date.now())
      localStorage.setItem('refresh_token', refreshToken)
    },
    destroyToken() {
      localStorage.removeItem('access_token')
      localStorage.removeItem('expiration')
      localStorage.removeItem('refresh_token')
    },
    isAuthenticated() {
      if (this.getToken()) {
        returntrue
      } else {
        returnfalse
      }
    },
    install(Vue) {
      Vue.prototype.$authStorage = this
    }
}

exportdefault authStorage

Which would allow me to use it like this outside of Vue,

importVuefrom'vue'importAppfrom'./App'import router from'./router'importAuthStoragefrom'./AuthStorage.js'Vue.config.productionTip = falseVue.use(AuthStorage)

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requireAuth)) {
    if (!AuthStorage.getToken()) {
      next({
        path: '/',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

And reference it like this inside of Vue:

created(){
  let token = this.$authStorage.getToken()
}

Here is an example.

Post a Comment for "Using Vuejs Plugin On The Main.js File"