jQuery toggles doesn't work inside VueJS

Hello everyone.

I have to create simple SPA with VueJS, and I made it.

I made 3 components that are representing pages, so I have shopHome, shopSingle and shopLenses.I paste the reuired code into each component, and as I said it works fine.

The problem is that I have some slideToggle() jQuery functions inside components, so when I try to toggle one element, I just got the blank page.

For e.g I toggle items in this way, using data-attributes

$('.toggle').click(function (e) {
    e.preventDefault();
    var tog = $(this).attr('data-class');
    $('.' + tog).slideToggle('fast');
    $(this).find('img').toggle();
}); 

This is mine VueJS code, it’s now in one file, I’m doing prototyping, so sorry on that :slight_smile:

var shopHome = Vue.extend({
	
	template: '#gotti-shop-template'

});

var shopSingle = Vue.extend({

	template: '#gotti-item-template'

});


var shopLenses = Vue.extend({

	template: '#gotti-lenses-template'

});

var Main = Vue.extend({});


var router = new VueRouter();

router.map({

	'/shophome': {

		component: shopHome

	},

	'/shopsingle': {

		component: shopSingle

	},

	'/shoplenses': {

		component: shopLenses

	}

});

router.start(Main, '#main');

Thanks.

Hey @bedakb,

Are you trying to toggle elements within one of the pages? Where are you putting that jQuery code that you’ve shown - is it inside of a <script> tag within the page template?

Hey

I have external JS file which contain jquery stuff and I include it at using script tags.

It sounds like the problem may be caused by one of the follow situations:

  • You’re including your external script file on the main HTML page, and it’s executing before the relevant HTML has been attached to the page by one of your page components.
  • You’re including your script in one of the component templates, and it’s being removed by Vue when the templates are parsed.

Try putting your jQuery code into the ready function of the page component. This should ensure it runs once the component has been created and inserted into the page.

var shopHome = Vue.extend({
	
  template: '#gotti-shop-template',

  ready: function() {

    $('.toggle').click(function (e) {
      e.preventDefault();
      var tog = $(this).attr('data-class');
      $('.' + tog).slideToggle('fast');
      $(this).find('img').toggle();
    });

  }

});
1 Like

Hey @fretburner, sorry for late response, It was weekend :slight_smile: ready did the trick, so I should do same for each component that I have (that use this jQuery part of code) ?

You could do, although if you are repeating the same code in each page it sounds like you should probably create a separate component for that which can be re-used wherever you need it.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.