[Vuejs]-Javascript not running when i bring html content from Api with Vue

0👍

TLDR

$("body").on("click","#mydiv", function(){alert('hello');});

Vue isn’t designed to be used this way. It’s uncommon for an API to return raw HTML too. Vue won’t parse the Javascript inside template. In fact if you try to include a script tag in any Vue template, you would get this error:

Templates should only be responsible for mapping the state to the UI.
Avoid placing tags with side-effects in your templates, such as
, as they will not be parsed.

If you can, avoid using v-html, change the API response so that it returns only the data needed for you to build the HTML, instead of the entire raw HTML. And you use the data inside Vue template.

But if you can’t, you can continue to try to use jquery to listen to the click event.

$("#mydiv").click(function(){alert('hello');}); doesn’t work probably because this line is executed before #mydiv is created.

This should work for you:

$("body").on("click","#mydiv", function(){alert('hello');});

This listens to click event for body , and execute the click callback if the click target is #mydiv.

Leave a comment