在 .js 文件中访问 Nuxt 插件

Access Nuxt plugins in .js files

假设我有一个脚本文件,foo.js:

function doStuff() {
   // how to access store and other plugins here?
}

export default { doStuff }

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

有多种调用自定义函数的方法,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。使用 context injection

声明自定义插件:

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) 使用combined injection

与方法 2 相同,但注入也可在 fetchasyncData 和存储模块内访问。 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()
  }
}

更多示例请参考documentation