click event not working inside div when v-html used - vue js

Viewed 1483

I have one contenteditable div and adding raw html including a click event using v-html. But the click event is not working in this case. Inspecting elements shows there's a click event on the div but still it won't work.

If I hard code any other div with click event inside contenteditable div then it's working. Don't know if I am doing it right. :

<div id="div_textarea2" v-html="temp_testing_div2" contenteditable="true"></div>


   data () {
    return {
          temp_testing_div2: `<div @click="ClickLine">Click this</div>`,

}
}


   ClickLine(){
   alert("Clicked");
}
1 Answers

@HermantSah v-html won't bind any Vue directives such as @click events. See docs here.

A workaround could be to have the @click event on the parent div and in your template string give the element something distinguishable, like an id.
You could then intercept the event and check which element was clicked. If the element matches the one in your template string do something etc. A rough example below.

<div id="div_textarea2" v-html="temp_testing_div2" @click="handleLineClick" contenteditable="true"></div>

...  
// in your script section
data() {
  return {
    temp_testing_div2: `<div id="temp_testing_div2">Click this</div>`,
  }
},
methods: {
  handleLineClick(e) {
    let clickedElId = e.target.id
    if (clickedElId === 'temp_testing_div2') {
      console.log("temp_testing_div2 clicked!", e)
    } else {
      console.log('another element was clicked')
    }
  }
}

It all feels a little messy though in my opinion. There may be an easier way of achieving what you desire.

Related