【问题标题】:Access Nuxt plugins in .js files在 .js 文件中访问 Nuxt 插件
【发布时间】:2019-04-17 13:53:43
【问题描述】:

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

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

export default { doStuff }

如果不将调用组件作为参数传递,我如何在上述脚本文件中访问 app 或安装的插件(如 store、i18n)?

【问题讨论】:

  • 请详细说明为什么默认插件格式不适合您? export default ({ app, store }) => { /* plugin code */ }
  • @aBiscuit 因为脚本文件不是插件
  • doStuff 应该从哪里调用?组件、商店或其他地方?这可能有助于确定更好的实施方法。
  • @aBiscuit 抱歉不清楚。主要来自组件。我想避免doStuff(this)、doStuff.call(this) 等。

标签: javascript vue.js nuxt.js


【解决方案1】:

有多种方法可以调用自定义函数,其中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 相同,但在 fetch、asyncData 和 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()
  }
}

更多示例请参考documentation。

【讨论】:

  • 感谢您的示例。假设我不想定义插件或 mixin,只是想访问 customHelpers.js 内的商店或类似内容。这可能吗?
  • 退后一步。一般来说,你想要做的是拥有一个动态绑定上下文的函数。必须有一个上下文访问点。它可以直接代替调用来完成(例如 doStuff.bind(this),或者直接将函数分配给组件的方法,因此 Vue 会为您绑定),也可以通过您开发的环境提供的方式来完成 - Nuxt。 js 在这种情况下,上面列出了。我认为在保持逻辑可维护性和可预测性方面没有更好的选择。
猜你喜欢
  • 2021-04-14
  • 2021-06-27
  • 2020-04-17
  • 2020-12-20
  • 2020-08-18
  • 2021-06-17
  • 2021-08-02
  • 2020-05-20
  • 1970-01-01
相关资源
最近更新 更多