Joh*_*han 3 javascript vue.js nuxt.js
假设我有一个脚本文件foo.js:
function doStuff() {
// how to access store and other plugins here?
}
export default { doStuff }
Run Code Online (Sandbox Code Playgroud)
如果不将调用组件作为参数传递,我如何在上面的脚本文件中访问app诸如store, 之类的或已安装的插件i18n?
有多种方法可以this通过引用调用自定义函数的组件来调用自定义函数。
1) 使用混入
自定义函数可以声明为方法并通过this.customMethod.
customHelpers.js
const customHelpers = {
methods: {
doStuff () {
// this will be referenced to component it is executed in
}
}
}
Run Code Online (Sandbox Code Playgroud)
component.vue
// component.vue
import customHelpers from '~/mixins/customHelpers'
export default {
mixins: [customHelpers],
mounted () {
this.doStuff()
}
}
Run Code Online (Sandbox Code Playgroud)
2. 使用上下文注入
声明自定义插件:
plugins/customHelpers.js
import Vue from 'vue'
Vue.prototype.$doStuff = () => { /* stuff happens here */ }
Run Code Online (Sandbox Code Playgroud)
并使用插件 nuxt.config.js
export default {
..., // other nuxt options
plugins: ['~/plugins/customHelpers.js']
}
Run Code Online (Sandbox Code Playgroud)
这使得方法在每个组件内都可用:
export default {
mounted () {
this.$doStuff()
}
}
Run Code Online (Sandbox Code Playgroud)
3) 使用联合注射
相同方法2,但注射也将是可访问的内部fetch,asyncData和内部存储模块。绑定到this可能会有所不同,因为上下文并非随处可用。
plugins/customHelpers.js
export default ({ app }, inject) => {
inject('doStuff', () => { /* stuff happens here */ })
}
Run Code Online (Sandbox Code Playgroud)
并使用插件 nuxt.config.js
export default {
..., // other nuxt options
plugins: ['~/plugins/customHelpers.js']
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
export default {
asyncData ({ app }) {
app.$doStuff()
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅文档以获取更多示例。