search

Home  >  Q&A  >  body text

Click event not working inside div when using v-html - vue js

I have a contenteditable div and use v-html to add the raw html including the click event. But in this case the click event doesn't work. Inspecting the element shows there is a click event on the div but it still doesn't work.

If I hardcode any other div with click event in contenteditable div then it works. Don't know if I'm doing this 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");
}

P粉521013123P粉521013123241 days ago469

reply all(1)I'll reply

  • P粉212114661

    P粉2121146612024-03-26 09:43:38

    @HermantSah v-html will not bind any Vue instructions, such as the @click event. See the documentation here.

    A workaround might be to set a @click event on the parent div and give the element something distinguishable, such as an id, in the template string.
    You can then intercept that event and check which element was clicked. If the element matches an element in the template string, do something, etc. Here's a rough example.

    ... // in your script section data() { return { temp_testing_div2: `
    Click this
    `, } }, 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 bit confusing to me. There may be an easier way to achieve your wish.

    reply
    0
  • Cancelreply