簡體   English   中英

在 .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) 使用混合

自定義函數可以聲明為方法並通過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和內部存儲模塊中也可以訪問注入。 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM