如何在Nuxt 2.15.8(Vue 2)中让自定义JS文件全局可访问
无需重复导入全局访问thingMap的实现方案(Vue 2 + Nuxt 2.15.8)
针对你的场景,这里有三种实用方案,按推荐程度排序:
方案一:Nuxt插件注入(官方推荐)
这是Nuxt最规范的全局变量注入方式,支持在组件、asyncData、fetch等所有场景下访问:
- 在项目
plugins目录下新建thing-map.js文件,写入以下代码:
import ThingMap from '~/lib/map/thing-map' export default ({ app }, inject) => { // 同时注入到Vue实例和Nuxt上下文 inject('thingMap', ThingMap) }
- 在
nuxt.config.js中注册该插件:
export default { plugins: [ '~/plugins/thing-map.js' ] }
- 使用示例:
- 组件的methods、模板中:
const icon = this.$thingMap.THING1.icon - asyncData/fetch钩子中(通过上下文访问):
async asyncData({ $thingMap }) { const thingName = $thingMap.THING2.name return { thingName } }
- 组件的methods、模板中:
方案二:挂载到Vue原型
如果习惯Vue传统的全局挂载方式,可直接把thingMap挂到Vue原型上:
- 在
plugins目录下创建thing-map.js:
import Vue from 'vue' import ThingMap from '~/lib/map/thing-map' // 所有组件实例均可通过this.$thingMap访问 Vue.prototype.$thingMap = ThingMap
- 同样在
nuxt.config.js中注册插件,组件内使用方式和方案一的组件内用法完全一致。
方案三:全局Mixin(仅作补充,不推荐)
通过全局Mixin将thingMap注入到所有组件的计算属性中,但会给所有组件增加额外属性,可能带来性能冗余:
- 创建
plugins/thing-map-mixin.js:
import Vue from 'vue' import ThingMap from '~/lib/map/thing-map' Vue.mixin({ computed: { thingMap() { return ThingMap } } })
- 在
nuxt.config.js注册插件后,组件内可直接通过this.thingMap或模板中{{ thingMap.THING3.name }}访问。
内容的提问来源于stack exchange,提问作者JeremyW
相关产品推荐
相关产品推荐

