1

I struggle to add a plugin in Nuxt.js. I have been looking to the doc and all kind of similar problems, but I got the same error: simpleParallax is not defined.

I tried different approach on all files

nuxt.config.js:

plugins: [
     {src: '~/plugins/simple-parallax.js', mode:'client', ssr: false} 
],

plugins/simple-parallax.js:

import Vue from 'vue';
import simpleParallax from 'simple-parallax-js';
Vue.use(new simpleParallax);

index.vue:

Export default {

     plugins: ['@/plugins/simple-parallax.js'],
     mounted() {
        var image = document.getElementsByClassName('hero');
        new simpleParallax(image, {
            scale: 1.8
        });
    }
}

Error message:

ReferenceError: simpleParallax is not defined.

2 Answers 2

3

The best solution I found out so far is to register simpleParallax on the Vue prototype like so in a plugin nuxt file with the name simple-parallax.client.js:

import Vue from 'vue';
import simpleParallax from 'simple-parallax-js';
Vue.prototype.$simpleParallax = simpleParallax;

Also my nuxt.config.js file if anyone would like to verify that as well:

plugins: [
  {src: '~/plugins/simple-parallax.client.js', mode: 'client', ssr: false}
],

I then have access to the plugin before instantiation in my case in the mounted life cycle of the primary or root component to grab the desired HTML elements and instantiate their individual parallax with the newly added global method this.$simpleParallax

For example I can then intiate a certain HTML element to have its parallax like so:

const someHTMLElement = document.querySelectorAll('.my-html-element');
const options = {...} // your desired parallax options
new this.$simpleParallax(someHTMLElement, options);
Sign up to request clarification or add additional context in comments.

Comments

-1

Actually you don't need to use plugin here. Just import simpleParallax from 'simple-parallax-js' in your component and init it with your image in mounted hook.

index.vue:

import simpleParallax from 'simple-parallax-js'

export default {
  ...
  mounted() {
    // make sure this runs on client-side only
    if (process.client) {
      var image = document.getElementsByClassName('thumbnail')
      new simpleParallax(image)
    }
  },
  ...
}

And don't forget to remove previously created plugin, it's redundant here.

3 Comments

Thank you, but when i do this i get " window is not defined from the plugin itself"...:/
@KelligJourdren, Oh, sure, I forget about SSR. I have updated the answer :)
@KelligJourdren so how did you solve this issue, did you register it as a plugin or did something else?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.