Home » vue » How do I inject an event listener to html generated via v-html

How do I inject an event listener to html generated via v-html

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have some html content in the form of a string variable log.htmlContent. I pass it into a div to be displayed via v-html. This div in particular only displays if log.htmlContent contains an img tag (http: will only appear in log.htmlContent if an img tag is present).

<div
    v-html="log.htmlContent"
    v-if="log.htmlContent.includes('http:')"
    class="textContent"
></div>

I would like to add a listener to the injected img tag that will run a function that passes the img tag’s src content as a parameter. Is this possible with vue? If so how. Thanks in advance for your help!

Answers:

A way to do that would be to create a watcher on your log.htmlContent, when a new image is coming in, you’ll have your string containing your img tag. You should be able then to get your src tag.

Here’s how you set a watcher :

watch: {
  log.htmlContent: function(val) {
    //Here you do the job to get your src tag
    alert(val);
  }
}

I’ve done the job in the following fiddle : https://jsfiddle.net/7yde4faz/1/

I’ll let you retrieve the src tag.

###

Figured it out! I just needed to create a listener in the div like so

<div
  v-html="log.htmlContent"
  v-if="log.htmlContent.includes('img src')"
  @click="displayFull($event)"
  class="textContent"
></div>

with $event I could pass the object I clicked as a parameter then use event.target.src to grab the src of the img when clicked.