Tips for executing a function whenever unfamiliar anchor elements are selected in Vue.js 3

I am utilizing a div with v-html to showcase data fetched from a database:

<div id="Content" v-html="
${Content}"></div>

Inside the presented ${Content}, there may be various a tags linking to external pages. I aim to parse these and attach an @click event handler to each one. For instance:

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

This needs to be transformed into:

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

Alternatively, I can direct Vue.js to execute the validateLink() function whenever any a tag is clicked within the div id="Content" element.

To capture all the a tags within the div, I use the following method:

const AnchorTags = document.getElementById('Content').getElementsByTagName('a');

However, I am unsure how to proceed in triggering the validateLink() function on clicking these tags.

Answer №1

When using v-html, the content is treated as plain HTML, meaning Vue directives cannot be placed inside.

To overcome this issue, consider utilizing event delegation. This involves attaching the handler to the parent element and inspecting the target (clicked) element for desired actions...

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/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9ceae9f9dcafb2aeb2ae">[email protected]</a>/dist/vue.global.js"></script>
<div id='app'>
  <div v-html="html" @click.stop.prevent="onClick">
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React Native - encountering undefined setState when passing data

I'm attempting to transfer data or items from one screen to another upon tapping the send button. However, the this.setState function in my "_onPress" method doesn't seem to be working correctly. When I tap the send button, the alert displays "un ...

The usage of $('').switchClass in IE8 may cause an error when the switched class includes a color property

I have the following unique css classes .swap-format{ background-color: green; } .swap-format1{ background-color: orange; } .swap-format2{ color: purple; } Using these classes, I want to create an animation on the given div <div id="swap-clas ...

What purpose does the symbol '$' serve in React component properties?

While delving into the world of styled-component, I encountered some difficulties with the 'adapting based on props' aspect. import './App.css'; import styled from 'styled-components' const PrimaryButton = styled.button` co ...

Italian calendar conversion for the react-multi-date-picker library

I recently integrated the react-multi-date-picker into my project, utilizing the multiple mode feature. However, I encountered an issue when trying to display the Italian calendar based on the language setting. Despite using locale="it", the calendar was n ...

How come the data I send gets converted to Undefined when working with Tabulator?

I am currently facing an issue with integrating JSON data as search results into my Tabulator. The goal is to display these search results in their respective columns within the Tabulator. Here is the code snippet I have implemented: <body> <div ...

Guide to crafting a javascript variable from MySQL through the power of PHP and AJAX

I am not very experienced in working with AJAX and javascript. I am currently trying to pass longitude and latitude values from a MySQL database to javascript, but it doesn't seem to be working as expected. Can anyone help me figure out what I might b ...

How can login errors be displayed in a Django application?

When I try to log into my website using the custom login page, entering the correct account details allows me access. However, if I input the wrong information, the page just refreshes with the username and password fields empty. Is there a way to display ...

The distinction between a keypress event and a click event

Due to my eyesight challenges, I am focusing on keyboard events for this question. When I set up a click event handler for a button like this: $("#button").on("click", function() { alert("clicked"); }); Since using the mouse is not an option for me, ...

JS/Docker - The attribute 'user' is not recognized in the context of 'Session & Partial<SessionData>'

I'm attempting to integrate express-session into my Node.js application running within Docker. I've come across several discussions on the topic: Express Session: Property 'signin' does not exist on type 'Session & Partial<Se ...

Automatically redirect users on page refresh using jQuery

I am attempting to use jQuery to detect when the user refreshes the page in order to redirect, but I can't seem to get it working. Can someone help me figure out what is wrong with this code? <?php include 'instagram.php'; ?> <! ...

The JavaScript function String.split() is generating an array filled with 20 empty strings

Attempting to replicate the functionality of jQuery's string-based HTML element determination, I employed a split function. However, rather than returning a list of values as intended, it produced an array containing twenty empty strings. console.l ...

Calculate the total amount based on the selected value from the radio button

For example, radiobutton A = value X, radiobutton B = value Y. Below is the code snippet I am utilizing: Javascript file: <script type="text/javascript" $(document).ready(function () { $("div[data-role='footer']").prepend(' ...

Struggling to retrieve JSON data from within an array

[ { "May": [ { "year": 1994, "date": "2" }, { "Sequence": 2, "Type": "Images" } ], "_id": "1122" } ] The issue I am facing is retrieving the id except for the "date" f ...

Learn how to create a dynamic React.useState function that allows for an unlimited number of input types sourced from a content management system

Currently, I am exploring the possibility of dynamically creating checkbox fields in a form using DatoCMS and the repeater module. My idea is to generate multiple checkbox fields based on the input from a text field in Dato as a repeater, which can then be ...

Is it possible for the scroll event to be triggered while scrolling only when a div element is used?

While utilizing window.onscroll to track scroll events during scrolling, I noticed that in certain Android devices the scroll event is only triggered after the scroll has completed. However, when monitoring scroll events within a specific div element, it ...

What is the best way to efficiently input identical data into multiple controllers ($scope) using just one call in AngularJS?

I have a situation where I am using a factory to make a call in two controllers on the same page. However, I want to avoid making an AJAX call twice. I tried using $q.defer(), but it doesn't seem to be working! Here is the code snippet: (function ...

Transferring variables from the $(document).ready(function(){}) to the $(window).load(function(){} allows for seamless and

Just think about if I successfully create percent_pass at the time of document.ready, how can I transfer that variable to window.load? $(document).ready(function() { jQuery(function() { var ques_count = $('.question-body').length; va ...

Converting CSS code into JavaScript

I am currently working with the following code: .mr15 > * margin-right: 15px &:last-child margin-right: 0 I need help translating this code to Javascript. Should I use JQuery or pure Javascript for this scenario? Thank you. ...

What is the best way to extract JSON data from an if statement?

Is there a way to access the 'data' variable outside of the if-else statement in the global scope? let request = new XMLHttpRequest(); request.open('GET', 'API Url'); request.send(); request.addEventListener('readystatec ...

JSON.stringify does not transform arrays into strings

It seems like I may have approached this task incorrectly, perhaps due to mishandling recursion. I'm unsure of where the mistake lies. You can view the example here. Below is the JavaScript code snippet - function propertyTest(currentObject, key) { ...