在 .js 文件中访问 Nuxt 插件 [英] Access Nuxt plugins in .js files
问题描述
假设我有一个脚本文件,foo.js
:
Let's say that I have a script file, foo.js
:
function doStuff() {
// how to access store and other plugins here?
}
export default { doStuff }
如果不将调用组件作为参数传递,我如何在脚本中访问诸如 app
或已安装的插件(如 store
、i18n
)像上面那样的文件吗?
Without passing the calling component as an argument, how can I access things like app
or installed plugins like store
, i18n
in a script file like the one above?
推荐答案
有多种方法可以调用自定义函数,this
是对调用它的组件的引用.
There are multiple ways to call custom function with this
being a reference to the component it was invoked in.
1) 使用 mixins
自定义函数可以声明为方法并通过this.customMethod
在组件中使用.
Custom function can be declared as a method and used within component via this.customMethod
.
customHelpers.js
const customHelpers = {
methods: {
doStuff () {
// this will be referenced to component it is executed in
}
}
}
component.vue
// component.vue
import customHelpers from '~/mixins/customHelpers'
export default {
mixins: [customHelpers],
mounted () {
this.doStuff()
}
}
2.使用 上下文注入
声明自定义插件:
plugins/customHelpers.js
import Vue from 'vue'
Vue.prototype.$doStuff = () => { /* stuff happens here */ }
并在nuxt.config.js
export default {
..., // other nuxt options
plugins: ['~/plugins/customHelpers.js']
}
这使得方法在每个组件中都可用:
This makes method available inside every component:
export default {
mounted () {
this.$doStuff()
}
}
3) 使用组合注入
与方法 2 相同,但也可以在 fetch
、asyncData
和 store 模块内部访问注入.this
的绑定可能会有所不同,因为上下文并非随处可用.
Same as method 2, but injection will be also accessible inside fetch
, asyncData
and inside store modules. Bindings to this
may vary, since context is not available everywhere.
plugins/customHelpers.js
export default ({ app }, inject) => {
inject('doStuff', () => { /* stuff happens here */ })
}
并在nuxt.config.js
export default {
..., // other nuxt options
plugins: ['~/plugins/customHelpers.js']
}
使用示例:
export default {
asyncData ({ app }) {
app.$doStuff()
}
}
有关更多示例,请参阅文档.
Please, refer to documentation for more examples.
这篇关于在 .js 文件中访问 Nuxt 插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!