Executing functions in Vue.js from dynamic HTML elements

There is a block of HTML coming from the server that needs to trigger a method or function when links embedded in the HTML are clicked.

The HTML is displayed in my .vue file as follows:

<template>
<div v-html="myhtml"></div>
</template>

<script>
import axios from 'axios'
export default {
  data () {
    return {
      myhtml: null
    }
  },
  created () {
     this.refreshHTML()
  },
   methods: {
     refreshHTML () {
        axios.get()// get my html
        this.myhtml = response.data
     },
     myFunction () {
       //do my function stuff here...
     }  
  }
}
</script>

I want to attach an onclick event in the fetched HTML to call my function like this:

<a href="myurl" onclick='event.preventDefault(); myFunction(this.href);'>link</a>

However, attempting to do so results in:

ReferenceError: Can't find variable: myFunction

Answer №1

This definitely raises some red flags in terms of best practices.

If I absolutely had to tackle it this way:

I would reluctantly place the function in the global scope (not ideal), and trigger it from the html event handler (also not recommended):

<template>
<div v-html="myhtml"></div>
</template>

<script>
import axios from 'axios'
export default {
  data () {
    return {
      myhtml: null
    }
  },
  created () {
     this.refreshHTML();
     window.myFunction = this.myFunction.bind(this);
  },
   methods: {
     refreshHTML () {
        axios.get()// retrieve my html
        this.myhtml = response.data
     },
     myFunction () {
       //perform necessary actions here...
     }  
  }
}
</script>

It might be worth considering transforming the html into vue components and utilizing them instead.

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

Sending a basic javascript variable to a PHP script

I need to send a basic JavaScript variable to another PHP file that serves as a controller within Laravel. For instance, the following code is from my blade.php file in Laravel: <script> function getLocation() { if (navigator.geolocat ...

Tips for displaying the remaining text in a dynamic and animated way

Initially, only a portion of the computed property known as showSupplierDescription is displayed. When a button is clicked, a method called showEntireSupplierDescription is triggered, toggling a boolean that controls whether the full or partial text is sho ...

MERN Stack - Table Ordering Solution

After spending countless hours trying to order the list items in the table, I am still unable to figure it out. The data is being fetched from a MongoDB using Axios. I am currently working with MongoDB Express React and NodeJS If you'd like to check ...

Tips for determining if an HTMLElement has already been created

One issue I'm facing is with a third party component that emits an "onCellEdit" event and passes a cell element as a parameter. My goal is to automatically select the entire text in the input element generated inside this cell when the event occurs. ...

Invoke a grandparent function from a nested component

In my ChildComponent, I have a simpleMethod function that calls a function from the parent component. However, I am facing an issue: A ViewComponent extends a LayoutComponent and is nested inside the ChildComponent. The structure looks something like this ...

Output either TRUE or FALSE from a function

Within this function, I am working with an array of objects and a specific value. The function iterates through the array using a forEach method to check if the provided value already exists in any of the objects within the array. If it is found, it shou ...

AngularJS: The art of object pushing

I have a small application where I need to read data from a JSON file, display it, and allow users to add records to it. Specifically, I have an array called condition within the patient object, and I want to insert a new item into this array based on user ...

Encountering issue with 'mongodb-connection-string-url'

As a beginner, I am struggling to understand the error message. When I try to run the app.js file, I receive the following log message. I read that I need to upgrade my MongoDB, but since I am using Windows 7, this seems impossible. PS G:\AWebDev&bsol ...

What is the best way to condense this code into just a single line?

Being a beginner in javascript, node.js, and express, my main query revolves around streamlining the code below into a single line within the function. exports.about = function(req, res){ var mytime = new Date(); res.render('about', {title: &a ...

Find the average value of an array containing objects

Imagine I have an array of objects like this: const BookDetails = [ { bookName: 'Harry Pottar', readingTime: 10663 }, { bookName: 'Harry Pottar', readingTime: 10986 }, { bookName: 'kaptura Tech', readingTime: 7034 } ] I ...

Is it possible to input tab characters in a TextField?

I am working with a multi-line MUI TextField and my objective is to input JSON text. However, I encountered an issue where pressing the tab key causes the component to lose focus and shift to the next element on the page. Is there a way to prevent the ta ...

What is the best way to verify that a Vue directive is triggered when hovering or mousing over an element?

My goal is to test the functionality of the b-tooltip.hover directive from bootstrap-vue when triggered on hover. Strangely, it appears that the directive is being called even without actually triggering the hover event using buttonWrapper.trigger('mo ...

Enhancing the WheelPicker feature in React Native JS by adding a string in front of a specific selected item

I am having an issue with adding the '$' sign before the selected WheelPicker item only. Currently, my code is adding the '$' sign in front of all Picker items. How can I resolve this problem? Thank you for any assistance. https://i.sst ...

Circular reference in Angular/TypeScript

I encountered a circular dependency issue in my Angular project and tried various solutions, including exporting all dependent classes from a "single file" as suggested here. Unfortunately, this approach did not work for me. I then explored other solutions ...

Check to see if a value is present in JavaScript and proceed with submitting the form

I have a situation where I am trying to capture the browser location and post it to another page. The problem I'm facing is that JavaScript takes some time to retrieve the browser location, causing the form to be submitted before the location is obtai ...

Countdown alert using JavaScript

Currently in my frontend code, I am utilizing angularjs as the javascript framework. In a specific section of my code, I need to display an error message followed by a warning message in this format: If a user inputs an incorrect month, then the following ...

Retrieve information based on ID with AJAX in JSON format on ASP.NET

Here is a method from my web service: List<object[]> List1 = new List<object[]>(); [WebMethod(EnableSession = true)] [System.Web.Script.Services.ScriptMethod(UseHttpGet = true, ResponseFormat = System.Web.Script.Services.Respons ...

The controller in AngularJS seems to be elusive and cannot be located

I've run into an issue while using angular-mock to inject my controller for unit testing. The error message I keep receiving is as follows: [$injector:unpr] Unknown provider: PatientRecordsControllerProvider <- PatientRecordsController This is h ...

How can you retrieve the <head> content from a remote website without being able to make any changes to that site?

Imagine I need to access the <head> tag of a remote website like YouTube. Whenever I attempt this, I encounter an error message: Access to XMLHttpRequest at ‘Website I am trying to access for the head section’ from origin ‘My Website’ has b ...

Error TS2349: The function cannot be called as it does not have a defined call signature. The type 'typeof renderIf' does not have any compatible call signatures

Based on the starter template found at https://github.com/react-native-training/reactxp-starter, I am just starting out with TypeScript! The issue seems to be related to the type in the renderIf function. I'm unsure where exactly the type should be s ...