Kellig Jourdren
Kellig Jourdren

Reputation: 11

plugin is not defined in instance.vue

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.

Upvotes: 1

Views: 583

Answers (2)

greensin
greensin

Reputation: 479

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);

Upvotes: 3

Andrew Vasylchuk
Andrew Vasylchuk

Reputation: 4779

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.

Upvotes: -1

Related Questions