Is there a way to call a Vue function from an onclick event in JavaScript?

Creating a vue component and trying to call a function defined in Vue methods using the onClick attribute when modifying innerHTML is resulting in an error message stating "showModal is not defined". Here is the showModal function where I'm simply trying to console some data:

methods: {
      showModal: function() {
            console.log("function is called")
            //this.$refs.myModalRef.show();
            //this.account=account;
        }
}

This is where I am attempting to call that function in JavaScript using onclick:

var inputText = document.getElementById("fileContents");
var innerHTML = inputText.innerHTML;
for(var i=0;i<this.violations.length;i++){
    var index=innerHTML.indexOf(this.violations[i]);
    if(index>0) {
        innerHTML = innerHTML.substring(0, index) +"<a href='#' onclick='showModal'>"+ "<span  style=\"background-color: yellow\">" + innerHTML.substring(index, index + this.violations[i].length) + "</span>" + "</a>" + innerHTML.substring(index + this.violations[i].length);
        inputText.innerHTML = innerHTML;
    }
}

Error message: Uncaught ReferenceError: showModal is not defined at HTMLAnchorElement.onclick ((index):1)

Am I calling it incorrectly?

Edit:

Credits to @Ferrybig - I can successfully call the function. However, another issue arises, where I want to pass the current word being modified as an argument to the function like so: onclick='myMethod(violations[i])'. I attempted to make the violations array global by doing:

window.violations=this.violations;

Yet, (variable i) which is the index of the current word in the array, isn't a global variable to be passed to 'myMethod' causing it to say (i is not defined). Since i is an incrementing index within the loop, setting it as global isn't feasible. Considering passing the current tag's index being edited to the 'myMethod' function for tracking purposes. Any alternative suggestions?

Answer №1

Utilizing Vue templates provides access to user-friendly syntaxes that can significantly reduce programming time. It is highly recommended to consider using Vue for rendering your web pages.

If, for some reason, you are unable to utilize Vue for rendering, there are alternative methods available:

To begin, create a lifecycle method within the 'created' hook that moves a reference of your Vue method to the global scope:

created(){window.myMethod =this.myMethod;}

After adding the method to the global scope, it can be easily referenced as mymethod within your plain JavaScript onclick handler.

It should be noted that this workaround does not support multiple instances of your Vue component. The complexities involved in supporting multiple instances make it more practical to stick with proper Vue components in such scenarios.

Answer №2

Ensure you include a Vue handler in your function call. Replace onclick with @click

For example:

@click="displayModal"

or, another option is

v-on:click="displayModal"

Answer №3

Hey there! Consider replacing href='#' with href="javascript:void(0)" and adding @click="showModal" instead. Give it a try - it might work!

Answer №4

To implement Vue syntax for onClick, refer to Method Event Handlers So

innerHTML = innerHTML.substring(0, index) +"<a href='#' v-on:click='showModal'>"+ "<span  style=\"background-color: yellow\">" + innerHTML.substring(index, index + this.violations[i].length) + "</span>" + "</a>" + innerHTML.substring(index + this.violations[i].length);

requires modification to

innerHTML = innerHTML.substring(0, index) +"<a href='#' v-on:click="showModal">"+ "<span  style=\"background-color: yellow\">" + innerHTML.substring(index, index + this.violations[i].length) + "</span>" + "</a>" + innerHTML.substring(index + this.violations[i].length);

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

Bootstrap Tags Input - the tagsinput does not clear values when removed

I am attempting to manually remove the input value from bootstrap-tags-input when the x button is clicked, but the values are not changing in either the array or the inputs. This is the code I have tried: $('input').tagsinput({ allowDuplica ...

Retrieve the response status using a promise

There is a promise in my code that sometimes results in an error response (either 400 or 403, depending on the user). I am trying to handle this situation by catching the response and implementing a conditional logic to execute different functions based on ...

The Cordova minification tool fails to compress files within the browser platform

I recently installed the cordova-minify plugin to compress the javascript code in my Cordova app. When I tried running the command: cordova build browser An output message appears: cordova-minify STARTING - minifying your js, css, html, and images. ...

Issue with async waterfall not triggering the next callback function when combined with a promise

async.waterfall(eventIDs.map(function (eventId) { console.log(eventId); return function (lastItemResult, nextCallback) { if (!nextCallback) { nextCallback = lastItemResult; las ...

"Stay current with real-time updates in seconds using React technology

Check out this code snippet: const currentTime = new Date().getTime(); const targetTime = new Date('November 15, 2020').getTime(); const difference = currentTime - targetTime; let seconds = Math.floor(difference / 1000) % 60; setInterval(functio ...

including a collection of values into a JSON data structure

Currently, I am iterating through some JSON data (grouped tweets from Twitter) to tally the frequency of specific keywords (hashtags) in order to generate an organized list of common terms. this (19) that (9) hat (3) I have achieved this by initial ...

how to ensure a consistent property value across all scopes in AngularJS

Here is my perspective <div ng-if="isMultiChoiceQuestion()"> <li class="displayAnswer" ng-repeat="choice in getMultiChoice() track by $index" ng-if="isNotEmpty(choice.text.length)"> <input type= ...

Encasing the window global variable within an AngularJS framework

Currently, I am encapsulating a global variable within a factory in order to make it injectable. Here is an example of how it's done: angular.module('Analytics').factory('woopra', [ '$window', function ($window) ...

Issues encountered with JSON formatting following jQuery ajax request

When my nodejs app receives data from a cordova app through a jQuery ajax call, the format is different. It looks like this: { "network[msisdn]": "+254738XXXXXX", "network[country]": "ke", "network[roaming]": "false", "network[simSt ...

Click on an element that is nested within another element that can also be clicked on

I'm facing a challenge while attempting to create an accordion inside another accordion. The issue arises with the nested elements and their behavior upon clicking. Essentially, I have a parent div with the class .applicant, which expands on click by ...

What is the method for including HTML special characters in d3.js?

I am attempting to incorporate the degree symbol in my HTML code using ° const degreeNum = d3 .select(`#windBox${order}`) .append("text") .attr("x", 250) .attr("y", 130) .style("font", "bold 50px sans-serif") ...

Is there a way to identify and count duplicate data-items within an array, and then showcase this information using a react view?

If we have an array like this: [{id: 1, name: "chocolate bar"}, {id:2, name: "Gummy worms"}, {id:3, name:"chocolate bar"}] Is there a way to show on the dom that we have "2 chocolate bars and 1 Gummy Worms"? ...

What is the best way to extract the value associated with the "first_name" key in the given object?

What is the best way to extract the value associated with the first_name key from the object below? { "first_name": "D", "last_name": "N", "phone_number": 1233414234 } ...

retrieving data from identical identifiers within a loop

Within my while loop, I am retrieving various dates for each event. <?php while( have_rows('_event_date_time_slots') ): the_row(); ?> <div> <h3 class="date-<?php echo $post->ID?>" name="tttdate<?php e ...

Verifying the timestamp of file submission in a form

My goal is to create an HTML form that allows users to send a file to my server, while also recording the exact time they initiated the file transfer. However, I'm facing an issue where only the time the file is received is being logged, rather than w ...

The use of set.has in filtering does not produce the desired outcome

I am attempting to use Set.has to filter an array in the following way: const input = [ { nick: 'Some name', x: 19, y: 24, grp: 4, id: '19340' }, { nick: 'Some name', x: 20, y: 27, grp: 11, id: '19343' }, { ...

Is there a period, question mark, apostrophe, or space in the input string?

Currently, I am in the process of developing a program that can determine if an input string includes a period, question mark, colon, or space. If these punctuation marks are not present, the program will return "false". However, if any of them are found, ...

Transitioning in Vue.js when data changes

Within the Vue documentation, there is only guidance on showing or hiding elements based on a condition. But what if you want to add a transition based on a change in value? For instance, displaying an upward arrow for 3 seconds when the new value is highe ...

Delivery person receiving biscuit but my internet browser doesn't seem to be getting it when I attempt to retrieve it

Currently, I am in the process of creating a website using Flask and React. The user is required to input an email and password on a form, which is then sent via axios.post to the backend. The backend checks if the email and password match with the databas ...

Encountering the error "undefined object" while using the yield keyword in JavaScript

var pi = document.getElementById("pi"); function * calculatePi(){ let q = 1; let r = 0; let t = 1; let k = 1; let n = 3; let l = 3; while (true){ if (4*q+r-t < n*t){ alert(n); yield n; ...