[英]Access Nuxt plugins in .js files
假设我有一个脚本文件foo.js
:
function doStuff() {
// how to access store and other plugins here?
}
export default { doStuff }
如果不将调用组件作为参数传递,我如何在上述脚本文件中访问app
或已安装的插件(如store
、 i18n
)?
有多种方法可以调用自定义函数,其中this
是对调用它的组件的引用。
1) 使用混合
自定义函数可以声明为方法并通过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']
}
这使得方法在每个组件中都可用:
export default {
mounted () {
this.$doStuff()
}
}
3) 使用组合注入
与方法2相同,但在fetch
、 asyncData
和内部存储模块中也可以访问注入。 this
的绑定可能会有所不同,因为上下文并非无处不在。
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()
}
}
请参阅文档以获取更多示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.