1

I tried to called my jquery custom slider inside vuejs on created but unfortunately it does't worked. It only works when i place the code inside on mounted but it stopped when i leave the page and come back to same page.

Here is my code.

export default {
  //This only worked on first load and never to work again on leaving the page and coming back!
    mounted() {
      require("./slider.js");
    },
        ...
    }

...

export default {
  //This never works!
    created() {
      require("./slider.js");
    },
        ...
    }

The slider.js

//Star slider
  (function($) {

  'use strict';

  var pluginName = 'slider',
    defaults = {
      next: '.slider-nav__next',
      prev: '.slider-nav__prev',
      item: '.slider__item',
      dots: false,
      dotClass: 'slider__dot',
      autoplay: false,
      autoplayTime: 3000,
    };

  function slider(element, options) {
    this.$document = $(document);
    this.$window = $(window);
    this.$element = $(element);
    this.options = $.extend({}, defaults, options);
    this.init();
  };

  slider.prototype.init = function() {
    this.setup();
    this.attachEventHandlers();
    this.update();
  };
  slider.prototype.setup = function(argument) {
    this.$slides = this.$element.find(this.options.item);
    this.count = this.$slides.length;
    this.index = 0;

    this.$next = $(this.options.next);
    this.$prev = $(this.options.prev);

    this.$canvas = $(document.createElement('div'));
    this.$canvas.addClass('slider__canvas').appendTo(this.$element);
    this.$slides.appendTo(this.$canvas);

    this.$dots = $(this.options.dots);
    this.$dots.length && this.createDots();
  };

  slider.prototype.createDots = function() {
    var dots = [];

    var dotClassName = this.options.dotClass;
    this.$element.children().find('.slider__item__title').each(function(__index, el) {
      var __title = $(this).text();
      dots[__index] = '<div data-index="' + __index + '" class="' + dotClassName + '">' + __title + '</div>';
    });
    this.$dots.append(dots);
  }

  slider.prototype.attachEventHandlers = function() {
    this.$element.on('prev.' + pluginName, this.prev.bind(this));
    this.$document.on('click', this.options.prev, (function(e) {
      this.$element.trigger('prev.' + pluginName);
    }).bind(this));

    this.$element.on('next.' + pluginName, this.next.bind(this));
    this.$document.on('click', this.options.next, (function(e) {
      this.$element.trigger('next.' + pluginName);
    }).bind(this));

    this.$element.on('update.' + pluginName, this.update.bind(this));
    this.$window.on('resize load', (function(e) {
      this.$element.trigger('update.' + pluginName);
    }).bind(this));

    this.$element.on('jump.' + pluginName, this.jump.bind(this));
    this.$document.on('click', ('.' + this.options.dotClass), (function(e) {
      var index = parseInt($(e.target).attr('data-index'));
      this.$element.trigger('jump.' + pluginName, index);
    }).bind(this));

    this.$element.on('autoplay.' + pluginName, this.autoplay.bind(this));
    this.$element.on('autoplayOn.' + pluginName, this.autoplayOn.bind(this));
    this.$element.on('autoplayOff.' + pluginName, this.autoplayOff.bind(this));
    this.$element.bind('prev.' + pluginName + ' next.' + pluginName + ' jump.' + pluginName, this.autoplay.bind(this));
    this.options.autoplay && this.$element.trigger('autoplayOn.' + pluginName);
  };

  slider.prototype.next = function(e) {
    this.index = (this.index + 1) % this.count;
    this.slide();
  };

  slider.prototype.prev = function(e) {
    this.index = Math.abs(this.index - 1 + this.count) % this.count;
    this.slide();
  };

  slider.prototype.jump = function(e, index) {
    this.index = index % this.count;
    this.slide();
  }

  slider.prototype.autoplayOn = function(argument) {
    this.options.autoplay = true;
    this.$element.trigger('autoplay.' + pluginName);
  };

  slider.prototype.autoplayOff = function() {
    this.autoplayClear();
    this.options.autoplay = false;
  }

  slider.prototype.autoplay = function(argument) {
    this.autoplayClear();
    if (this.options.autoplay) {
      this.autoplayId = setTimeout((function() {
        this.$element.trigger('next.' + pluginName);
        this.$element.trigger('autoplay.' + pluginName);
      }).bind(this), this.options.autoplayTime);
    }
  };

  slider.prototype.autoplayClear = function() {
    this.autoplayId && clearTimeout(this.autoplayId);
  }

  slider.prototype.slide = function(index) {
    undefined == index && (index = this.index);
    var position = index * this.width * -1;
    this.$canvas.css({
      'transform': 'translate3d(' + position + 'px, 0, 0)',
    });
    this.updateCssClass();
  };

  slider.prototype.update = function() {
    this.width = this.$element.width();
    this.$canvas.width(this.width * this.count);
    this.$slides.width(this.width);
    this.slide();
  };

  slider.prototype.updateCssClass = function() {
    this.$slides
      .removeClass('x__slider-active')
      .eq(this.index)
      .addClass('x__slider-active');

    this.$dots
      .find('.' + this.options.dotClass)
      .removeClass('x__slider-active')
      .eq(this.index)
      .addClass('x__slider-active');
  }

  $.fn[pluginName] = function(options) {
    return this.each(function() {
      !$.data(this, pluginName) && $.data(this, pluginName, new slider(this, options));
    });
  };

})(window.jQuery);

$('#x__slider').slider({
  prev: '#x__slider-prev',
  next: '#x__slider-next',
  dots: '#x__slider-dots',
  autoplay: true,
});
//End slider 

1 Answer 1

1

Mounted vs created

You noticed that your code does not work when you put it in the created lifecycle hook. To figure out why that is, we need to look at the lifecycle hooks in depth. Your slider works by finding an element, then transforming that into a slider.

When the created hook is ran, there is no component rendered yet. There is only html from your component just after the beforeMount lifecycle hook. The first lifecycle hook you can use after that is the mounted hook.

It only runs once, but why?

You use require(..) to run the code for your slider. Requiring your slider file runs an IIFE. After it has been included, there is no need to run it again. When you load your slider again, the file is loaded from memory, as it has already been "required" before.

It would be better to require the code outside your component lifecycle hooks completely, and then use some initialisation function that is exported from the file.

How to fix this?

I recommend against using jQuery within a Vue application. Both jQuery and Vue manipulate the DOM. There's nothing Vue can't do that jQuery can do, but you may need to rethink how you structure your elements. There are also several premade sliders out there if you don't want to write anything yourself.

If you need to get it to work with jQuery, your best bet is to slightly change your slider.js file to export the initialisation code at the bottom.

export default function (element) {
  $(element).slider({
    prev: '#x__slider-prev',
    next: '#x__slider-next',
    dots: '#x__slider-dots',
    autoplay: true,
  });
}

Instead of using require, just import it at the top of the component:

<script>
  import sliderInit from './slider';
  
  export default {
    // ...

Change your template to include a ref on the element. This allows you to reference a DOM element without risking duplicate ids on the page.

<template>
  <div ref="slider">
    <div class="slide">
      <!-- You get the idea -->
    </div>
  </div>
</template>

Now we only need to initialise the slider. The best way to do that is to execute the function we just imported in the mounted hook. You may need to wait a tick for the reference to take hold

mounted () {
  // Option 1
  sliderInit(this.$refs.slider);

  // Option 2
  this.$nextTick(() => {
    sliderInit(this.$refs.slider);
  });
}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.