简体   繁体   中英

Access Nuxt plugins in .js files

Let's say that I have a script file, foo.js :

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

export default { doStuff }

Without passing the calling component as an argument, how can I access things like app or installed plugins like store , i18n in a script file like the one above?

There are multiple ways to call custom function with this being a reference to the component it was invoked in.

1) Using mixins

Custom function can be declared as a method and used within component via 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. Using context injection

Declare custom plugin:

plugins/customHelpers.js

import Vue from 'vue'

Vue.prototype.$doStuff = () => { /* stuff happens here */ }

And use plugin in nuxt.config.js

export default {
  ..., // other nuxt options
  plugins: ['~/plugins/customHelpers.js']
}

This makes method available inside every component:

export default {
  mounted () {
    this.$doStuff()
  }
}

3) Using combined injection

Same as method 2 , but injection will be also accessible inside fetch , asyncData and inside store modules. Bindings to this may vary, since context is not available everywhere.

plugins/customHelpers.js

export default ({ app }, inject) => {
  inject('doStuff', () => { /* stuff happens here */ })
}

And use plugin in nuxt.config.js

export default {
  ..., // other nuxt options
  plugins: ['~/plugins/customHelpers.js']
}

Usage example:

export default {
  asyncData ({ app }) {
    app.$doStuff()
  }
}

Please, refer to documentation for more examples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM