Tengo un div con v-html que muestra datos de una base de datos:
<div id="Content" v-html=" ${Contenido} "></div>
Dentro del ${Content} que se presenta, puede haber cualquier número a etiquetas con enlaces a otras páginas externas. Necesito analizarlos y luego agregar un controlador @click a cada uno de ellos. Un ejemplo sería:
<p>Calm down, Marty, I didn't disintegrate anything. The <a href="example.com/m">molecular structure</a> of Einstein and the car are completely intact. They wanted me to build them a bomb, so I took their <a href="example.com/d">plutonium</a> and in turn gave them a shiny bomb case full of used pinball machine parts.
Para transformarse en esto:
<p>Calm down, Marty, I didn't disintegrate anything. The <a @click="validateLink()" href="example.com/m">molecular structure</a> of Einstein and the car are completely intact. They wanted me to build them a bomb, so I took their <a @click="validateLink()" href="example.com/d">plutonium</a> and in turn gave them a shiny bomb case full of used pinball machine parts.
O, alternativamente, simplemente instruya a Vue.js para que ejecute validateLink() cada vez que se haga clic en a etiqueta dentro de la div id="Content" .
Puedo obtener todas las etiquetas a dentro del div así:
const AnchorTags = document.getElementById('Content').getElementsByTagName('a'); Pero no sé cómo hacer que la función validateLink() se ejecute al hacer clic en estas etiquetas.
El contenido de v-html se trata como HTML simple: no puede colocar directivas de Vue dentro.
Afortunadamente para usted, este problema específico se puede resolver fácilmente mediante la delegación de eventos, por ejemplo, adjuntando el controlador al elemento principal + inspeccionando el elemento de destino (clic)...
const app = Vue.createApp({ data() { return { html: `<p>Calm down, Marty, I didn't disintegrate anything. The <a href="example.com/m">molecular structure</a> of Einstein and the car are completely intact. They wanted me to build them a bomb, so I took their <a href="example.com/d">plutonium</a> and in turn gave them a shiny bomb case full of used pinball machine parts.` } }, methods: { onClick(ev) { if(ev.target.tagName === 'A') { console.log('Anchor clicked -', ev.target.href) } } } }) app.mount('#app') <script src="https://unpkg.com/vue@3.2.2/dist/vue.global.js"></script> <div id='app'> <div v-html="html" @click.stop.prevent="onClick"> </div> </div>