有多种方法可以调用自定义函数,this
是对其所在组件的引用。
1)使用mixins
自定义函数可以声明为方法,并通过 this.customMethod
在组件内部使用。
customHelpers.js
const customHelpers = {
methods: {
doStuff () {
}
}
}
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 = () => { }
在 nuxt.config.js
文件中使用插件
export default {
...,
plugins: ['~/plugins/customHelpers.js']
}
这使得该方法在每个组件内都可用:
export default {
mounted () {
this.$doStuff()
}
}
3) 使用 组合注入
与方法2相同,但注入也可以在fetch
、asyncData
和store模块中访问。由于上下文无处不在,因此对this
的绑定可能会有所不同。
plugins/customHelpers.js
export default ({ app }, inject) => {
inject('doStuff', () => { })
}
在 nuxt.config.js
中使用插件
export default {
...,
plugins: ['~/plugins/customHelpers.js']
}
使用示例:
export default {
asyncData ({ app }) {
app.$doStuff()
}
}
请参考
文档获取更多示例。
export default ({ app,store })=> { /* 插件代码 */ }
- aBiscuitdoStuff
应该从哪里调用?组件、存储还是其他地方?这可能有助于确定更好的实现方法。 - aBiscuitdoStuff(this)
,doStuff.call(this)
等方法。 - Johan