问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/53302905/access-nuxt-plugins-in-js-files