访问 .js 文件中的 Nuxt 插件

2024-05-11

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

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

export default { doStuff }

如果不将调用组件作为参数传递,我如何访问诸如app或安装了类似的插件store, i18n在像上面这样的脚本文件中?


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

1)使用mixins https://v2.vuejs.org/v2/guide/mixins.html#Basics

自定义函数可以声明为方法并通过以下方式在组件内使用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. 使用上下文注入 https://nuxtjs.org/guide/plugins/#inject-in-root-amp-context

声明自定义插件:

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)使用联合注射 https://nuxtjs.org/guide/plugins/#combined-inject

与方法相同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()
  }
}

请参阅文档 https://nuxtjs.org/guide/plugins/#combined-inject了解更多示例。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

访问 .js 文件中的 Nuxt 插件 的相关文章

随机推荐