全局定义在 vue.js 中不起作用
global definition does not work in vue.js
我试过如下所示全局导入和定义库,但不知何故它无法识别全局变量。
在 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/>'
})
在Signup.vue,
...
const payload = VueJwtDecode.decode(res.jwt);
...
并且错误显示未定义 VueJwtDecode。
作为document,在你的组件中,你需要使用
this.$jwtDec(res.jwt)
而不是
VueJwtDecode.decode(res.jwt);
如果您尝试使用 VueJwtDecode
的命名引用,您需要在 Signup.vue 组件中重新导入该库,因为 Signup.vue 不理解 VueJwtDecode
表示.
import VueJwtDecode from 'vue-jwt-decode'
const payload = VueJwtDecode.decode(res.jwt);
但是,由于您已经全局安装了该库,因此它已安装到 Vue 实例中,这意味着它可以从组件中的 this
上下文中获得。因此,您也可以从组件上下文访问它而无需重新导入:
const payload = this.$jwtDec(res.jwt);
我试过如下所示全局导入和定义库,但不知何故它无法识别全局变量。
在 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/>'
})
在Signup.vue,
...
const payload = VueJwtDecode.decode(res.jwt);
...
并且错误显示未定义 VueJwtDecode。
作为document,在你的组件中,你需要使用
this.$jwtDec(res.jwt)
而不是
VueJwtDecode.decode(res.jwt);
如果您尝试使用 VueJwtDecode
的命名引用,您需要在 Signup.vue 组件中重新导入该库,因为 Signup.vue 不理解 VueJwtDecode
表示.
import VueJwtDecode from 'vue-jwt-decode'
const payload = VueJwtDecode.decode(res.jwt);
但是,由于您已经全局安装了该库,因此它已安装到 Vue 实例中,这意味着它可以从组件中的 this
上下文中获得。因此,您也可以从组件上下文访问它而无需重新导入:
const payload = this.$jwtDec(res.jwt);