有多种方法可以调用自定义函数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了解更多示例。