How to access store context within a plugin in nuxt?
First question : why it is print now ? I did not call it at all.
Because Nuxt calls it for you.
Nuxt calls every .js files inside ./plugins folder, before instantiating the root vue.js application.
https://nuxtjs.org/guide/plugins
If you want to use logFn.js
as a utility function or something, you should put it in ./assets or create your own util folder.
Second question : why this error regarding the log I had previously?
Because you didn't pass the required argument.
The cause could be much easier to locate, if written like below.
Your code equals to:
export default function (context) {
console.log('store is', context.store)
}
The function needs an argument.
When the Nuxt calls it, Nuxt gives it context, so you can access store.
When you called that function in your page, you didn't pass an required argument, so that error occurred.
So what should you do ?
Create ~/assets/js/logFn.js
.
export default (store) => { // <- not { store }, but store
console.log('store is', store)
}
Call it like this, in your page.vue
<script>
import logFn from '~/assets/js/logFn.js'
export default {
methods: {
onClick () {
logFn(this.$store)
}
}
}
</script>
Hope it works.
flrnt
Updated on June 04, 2022Comments
-
flrnt almost 2 years
I try to add third party code and use it in my Nuxt app. Basically I wrote a plugin under
@/plugins/vendorCode/logFn.js
which contains a dumb function :export default ({ store }) => { console.log('store is', store) }
As you can see I try to access store and perform later some mutation. That's my next step. But for now I'm stuck.
In my Vue Component, I've a button calling the logFn, here's what I did :
<script> import logFn from '@/plugins/vendorCode/logFn.js' export default { methods: { onClick () { logFn() } } } </script>
So far so good. Once page reload, I can see the result of my logFn in the console, with the store object.
First question : why it is print now ? I did not call it at all.
Then I click the button and got an error :
TypeError: Cannot read property 'store' of undefined
.Second question : why this error regarding the log I had previously?
Thank you for your help