Search code examples
javascriptvue.jspluginsglobal-variableslibraries

global definition does not work in vue.js


I have tried to import and define a library globally as below, but somehow it does not recognize the global variable.

in main.js,

import Vue from 'vue'
import App from './App'
import router from './router'
import VueJwtDecode from 'vue-jwt-decode'

Vue.config.productionTip = false
Vue.use(VueJwtDecode)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

in Signup.vue,

...
const payload = VueJwtDecode.decode(res.jwt);
...

and the error shows that VueJwtDecode is not defined.


Solution

  • If you are trying to use the named reference of VueJwtDecode, you need to reimport the library in your Signup.vue compoenent since Signup.vue doesn't understand what VueJwtDecode means.

    import VueJwtDecode from 'vue-jwt-decode'
    const payload = VueJwtDecode.decode(res.jwt);
    

    However, since you have globally installed the library, it has been installed to the Vue instance, meaning that it is available from the this context within your component. As a result, you can also access it from the component context without reimporting:

    const payload = this.$jwtDec(res.jwt);