Home > Mobile >  How to access "this" context (Vue/Nuxt instance) in a VanillaJS file?
How to access "this" context (Vue/Nuxt instance) in a VanillaJS file?

Time:11-04

I have a function inside a .js file in a nuxt 2 project.

Basically I need to use a nuxt module property from nuxt.config like this this.nuxt.options. inside a function in a normal .js file.

For example:

aNormalJsFile.js

if (this.nuxt.options.module.triggers.isActive) {
  // do something
}

But now I can't because it doesn't know what is Nuxt of course. I'm getting this error:

Cannot read properties of undefined (reading 'nuxt')

CodePudding user response:

If you want to inject a Vue/Nuxt instance inside of a .js file (vanilla JS), you can follow this helper function approach

/src/utils/printCoolNumber.js

export const printIt = (VueInstance) => console.log(VueInstance.coolNumber)
// ☝           
  • Related