Click event not working inside div when using v-html - vue js
P粉521013123
P粉521013123 2024-03-25 20:48:41
0
1
470

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粉521013123
P粉521013123

reply all(1)
P粉212114661

@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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template