在.js文件中访问Nuxt插件

3
假设我有一个脚本文件foo.js:
function doStuff() {
   // how to access store and other plugins here?
}

export default { doStuff }

在不将调用组件作为参数传递的情况下,我如何在上面的脚本文件中访问诸如app或已安装插件storei18n等内容?


请详细说明为什么默认插件格式不能满足您的需求? export default ({ app,store })=> { /* 插件代码 */ } - aBiscuit
@aBiscuit 因为脚本文件不是插件。 - Johan
doStuff 应该从哪里调用?组件、存储还是其他地方?这可能有助于确定更好的实现方法。 - aBiscuit
@aBiscuit 很抱歉我没有解释清楚。主要是从组件方面考虑。我想避免 doStuff(this),doStuff.call(this) 等方法。 - Johan
1个回答

5

有多种方法可以调用自定义函数,this 是对其所在组件的引用。

1)使用mixins

自定义函数可以声明为方法,并通过 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相同,但注入也可以在fetchasyncData和store模块中访问。由于上下文无处不在,因此对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()
  }
}

请参考文档获取更多示例。

1
谢谢你的示例。假设我不想定义插件或混合,只想在 customHelpers.js 中访问 store 或类似的内容,这是否可能? - Johan
退一步说,通常你想做的是有一个带有动态绑定上下文的函数。必须有上下文的访问点。可以在调用的地方直接完成(例如doStuff.bind(this)),或者将函数直接分配给组件的方法,这样Vue会为您进行绑定,也可以通过您开发环境提供的方式进行操作 - 在这种情况下是Nuxt.js,如上所列。我认为在保持逻辑可维护性和可预测性方面不会有更好的选择。 - aBiscuit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接