Is it possible to add a click handler function to a dynamically generated link in Vue?

When working with Vue components, I receive dynamic messages from the server:

module.exports = {
  data() {
     return: { windowText: '' }
  },

  methods: {

    showCancelEntrieWindow(){
      this.$http.post('/page', {'number' : '123'})
          .then(response => {
               responseText = response.data.message;

               this.windowText = responseText.replace(
                  new RegExp("class='action'", 'g'), 
                  'v-on:click="myclick"'
               ); 

           });
    },
    myclick(){
       console.log('clicked!');
    }
  }
};

The message contains a link with the class "action".

For example:

response.data.message = 'Some text... <a class="action" href="/test">test</a>';

In the template:

<div v-html="windowText"></div>

I want to add a click handler function to this link. However, directly editing the response.data.message is not an option.

I attempted to modify the response by replacing the class attribute like this:

this.windowText = responseText.replace(
    new RegExp("class='action'", 'g'), 
    'v-on:click.stop="myclick"'
);

Unfortunately, this approach did not work as expected. Can anyone provide assistance on how to achieve this?

Additionally, please keep in mind that direct modification of response.data.message is not allowed.

Answer №1

v-html does not compile the template, so simply replacing the class with a Vue directive will have no effect.

Instead, you can utilize a native event listener for this purpose.

new Vue({
  el: "#app",
  data:{
    windowText: null,
    someValueSetOnClick: null
  },
  methods:{
    onHtmlClick(event){
      // Verify that the click is from our v-html element to avoid handling unrelated clicks within Vue
      if (!event.target.classList.contains("action"))
        return;

      event.stopPropagation();
      event.preventDefault();
      this.someValueSetOnClick = "Clicked";
    }
  },
  mounted(){
    this.windowText = 'Some text... <a class="action" href="/test">test</a>'

    // Attach a native event listener to the Vue element.
    this.$el.addEventListener("click", this.onHtmlClick)
  }
})

Check out an example here.

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

Issue: Unable to utilize import statement outside a module as per the guidelines of the vue-test-utils official tutorial

I'm struggling to get Vue testing set up with vue-test-utils and jest. I followed the installation guide at https://vue-test-utils.vuejs.org/installation/#semantic-versioning, but can't seem to figure out what's wrong. Here's what I&apo ...

Top technique for extracting json files from post requests using nodejs

Situation: I'm running a Node.js REST server that receives JSON files, parses them, and inserts them into a database. With an anticipated influx of hundreds of requests per second. Need: The requirement is to only perform insertions by parsing the JS ...

Issue with relative templateUrl in Angular 2 not resolving paths

As I embark on creating my first Angular 2 app, I'm faced with the task of setting my template in an HTML file using `templateUrl`. Currently, both the component.ts and view.html are stored in the same folder under src/ directory. Here's what I ...

Creating a sleek animation with JQuery for a dynamic-width div

Here is a snippet from my latest project. Take a look at the demonstrationFIDDLE. In this project, I have created a list with buttons: <a href="#f1" class="bt">1 <div class="show">Computers Networking</div> </a> When you ...

How to retrieve the value of an observable from a regular JavaScript array in Knockout JS?

Context In my project, I am working with a plain JavaScript array that starts off empty but gets populated with Knockout observables later on. These values are numbers and I need to compare them with values in another Knockout observable array. The issue ...

Tips for Printing a div Element with Horizontal Scrollbars

My webpage has both vertical and horizontal scroll bars, but when I use window.print(), it only prints the visible content in the window. Is there a way to print the entire scrollable content within the window? ...

Determining in Express.js whether headers have been sent or not

As I develop a library that involves setting headers, I aim to provide a personalized error message in case the headers have already been sent. Rather than simply letting it fail with the default "Can't set headers after they are sent" message from No ...

Retrieve the specific item from an object array using the designated key

I am working with an array of objects and my goal is to retrieve the object that has the key "Z". While I could iterate through the array, checking each key one by one until finding a match, I believe there might be a more efficient solution than my curre ...

What is the purpose of the "modal-backdrop fade show" element remaining visible after the associated component is unmounted, and what is the best way to eliminate or disable this div?

Scenario I have a Vue component that includes a child component responsible for displaying a modal. Toggling the isShowModal boolean either through a button click or Vue devtools successfully displays and hides the modal as expected. However, upon tryin ...

What are the necessary requirements for executing the command "npm run build"?

What are the requirements for executing npm run build? I am currently working on a Vue project. My goal is to deploy it onto a new server. Will running npm install be sufficient for this purpose? ...

Using Vue.js to share events and data across various components

I am currently working on an application that features a Google map with a places autocomplete controller, similar to the example provided by Google at this link. Whenever an address is searched or selected, or when the map bounds are changed, I trigger a ...

Delete the generated thumbnails from the input JavaScript file

One issue I'm facing is that I have written JavaScript code to generate a thumbnail when a user uploads an image. Now, I would like to implement a feature that allows the user to click on an "X" button to delete the uploaded image. This is the existi ...

Using VueJS: Passing a variable with interpolation as a parameter

Is there a way to pass the index of the v-for loop as a parameter in my removeTask function? I'm looking for suggestions on how to achieve this. <ol class="list-group"> <li v-for="task in tasks" class="list-group-item"> ...

Multiple card displays not working with Javascript Fetch API

I wrote a script that retrieves data from a URL and then organizes it into tables for display to the user. Initially, the script functioned correctly. However, I decided to enhance its flexibility by introducing two parameters - name and HTML div name wher ...

Tips for displaying identical tab content across various tabs using jquery or javascript

For instance, if we have tabs labeled as 1, 2, 3, 4, and 5, and a user has selected tabs 2, 3, and 4, how can we display the same content for those tabs while showing different content for the remaining ones? ...

The input given to Material UI autocomplete is incorrect, even though the getOptionSelect parameter already exists

I'm currently working on creating my own version of the Google Places autocomplete found in the Material UI documentation. While I have successfully implemented the autocomplete feature and am able to update my component's state with the result, ...

Bringing in functions - NodeJS - non-HTML

Currently, I am in the process of learning automation for my job and have hit a roadblock. In times like these, stackoverflow has proven to be a life-saving resource :) My current task involves writing a Selenium test in VisualStudio using JavaScript (nod ...

Upgrading from Vuetify 2 to 3 involves replacing the deprecated styles like .v-application, rounded, and flat with

I need help with upgrading from Vuetify/Vue 2 to Vue 3. I don't have much experience in front-end development, but I am responsible for updating some old code to keep things running smoothly. The migration guide is not very clear and assumes a certain ...

What are some ways to condense this Angular/TS code for improved performance and readability?

I am in need of assistance with refactoring a method called getBaseUrl(). This method assigns a specified string value to this.baseURL based on the input serviceType. getBaseUrl(serviceType: string, network?: string) { // Method logic to determine base ...

Executing the main process function

One of the challenges I'm facing is calling a function from the main process in Javascript while a button is clicked in another file. Here is the code snippet: Main.js const electron = require( 'electron') const {app, BrowserWindow} = elec ...