[英]Access Nuxt plugins in .js files
假設我有一個腳本文件foo.js
:
function doStuff() {
// how to access store and other plugins here?
}
export default { doStuff }
如果不將調用組件作為參數傳遞,我如何在上述腳本文件中訪問app
或已安裝的插件(如store
、 i18n
)?
有多種方法可以調用自定義函數,其中this
是對調用它的組件的引用。
1) 使用混合
自定義函數可以聲明為方法並通過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.使用上下文注入
聲明自定義插件:
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) 使用組合注入
與方法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()
}
}
請參閱文檔以獲取更多示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.