Dynamically changing click events in VueJS can be achieved using a combination of

Once component B has finished loading, I trigger an "emit" event to notify component A using EventBus.

When A receives the event with a value of "on", it updates a specific data value to true.

This value is stored in a computed property and can only be accessed using an "a tag" if it is true.

However, even though the value changes to true, the click event still returns "return false;"

Is there a way to make the click event behave dynamically in VueJS?

Component B

...
this.$EventBus.$emit("Loading");
...

Component A

<template>
    <a href="javascript:void(0)" @click="completed ? btnFinish : 'return false;'">Complete</a>
</template>
<script>
    data() {
        return {
            loading: false,
        }
    },
    mounted() {
        this.$EventBus.$on('Loading', ()=>{
            this.loading = true;
        });
    },
    computed: {
        completed() {
            return this.loading
        }
    }
</script>

Answer №1

It appears there may be a misunderstanding regarding the functionality of this click listener:

@click="completed ? btnFinish : 'return false;'"

Essentially, the 'return false;' portion serves no real purpose other than acting as filler text after the colon. You could easily replace it with null, or even switch it to an && instead of a ?:.

Furthermore, the value for an @ listener can be either a function or an expression. For instance, using a function would look like this:

@click="btnFinish"

When passing a function, it acts as the event handler.

However, in this case, an expression is being passed instead. Vue automatically wraps expressions in a function. Therefore, writing something like this:

@click="completed ? btnFinish : 'return false;'"

Vue will convert it into a listener function like so:

function ($event) {
  return completed ? btnFinish : 'return false;'
}

It's important to note that btnFinish references a method but isn't being invoked. To make it work as intended, the parentheses need to be included:

@click="completed ? btnFinish() : 'return false;'"

Alternatively:

@click="completed && btnFinish()"

Even better, you could encompass the entire logic within a method:

@click="onClick"
methods: {
  onClick () {
    if (this.completed) {
      this.btnFinish()
    }
  }
}

Answer №2

Discover an alternative method begin by locating the button using its unique identifier

 const customButton = document.getElementById('buttonId');
 customButton.onclick = newApproach

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

retrieving a promise fails during the set interval

Hey there! I'm currently a computer science student and still getting the hang of things. Recently, I encountered an issue that I can't seem to solve on my own. The problem is related to fetching data from my MongoDB database every few seconds an ...

How to Trigger a Callback Function in Angular Template?

Within my directive for tables, I have the ability to output values based on specific properties. For example: <tr ng-repeat="item in table.data"> <td ng-repeat="column in table.columns"> <i ng-if="column.type === 'icon&apo ...

What is the benefit of using $q.all() with a single promise in AngularJS?

As I delve into this codebase, one snippet keeps popping up: $q.all([promise]).then(responseFunc); However, I find this confusing. After reading the documentation, I wonder why not simply use the following, as it's just a single promise... promise. ...

Alter Text Using Typewriter

Recently, I have been experimenting with code on my glitch website, trying to create typewriter text. Thanks to help from a user on StackOverflow, I was able to achieve this effect successfully. However, I am now facing a new challenge. My goal is to make ...

Is it possible for me to create a nested component without having to make a new file

What I desire: Home.vue <template> <div> <p>{{message}}</p> <ChildComponent/> </div> </template> <script setup> import { ref, defineComponent } from 'vue'; let message = r ...

Switching the Vue image on Routerlink's isExactActive feature

Is there a way to display different images based on whether a link is active or not? <router-link to="/"> <img src=" :active = isExactActive ? pic_active.png : pic_inactive.png}}" /> //Something along these lines ...

What is the correct way to chain custom callback functions using .queue()?

I am currently grappling with the concept of chaining custom functions: My code snippet looks like this: show_loader(0, function() { open_box($target_open, event.value, '.wide-col', function() { hide_loader(function() { ...

accessing elements in a loop in vuejs

I am trying to create a rating system using Vue.js and the v-for directive. Here is the code I have: <div class="rating-container"> <input type="radio" name="star" value="5" id="star-5"> <label class="star-radio" for="star-5">5&l ...

Automatically close an element when you click on a different element

Hello everyone! I need some help again. I'm working on a script that displays an overlay when a menu item is clicked. Within this menu, there is a modal contact form with a close icon or anchor that should appear when clicked. My goal is to have the o ...

Prevent rapid event triggers with a jQuery slider

I am currently working with an event function in JavaScript that involves a slider and a tooltip element. Here is the code snippet: //Hide the Tooltip initially tooltip.hide(); //Initialize the Slider slider.slider({ ...

Include jQuery, jQuery UI, and plugins seamlessly to avoid any version conflicts

My goal is to inject my custom code into a webpage using a bookmarklet. This code requires jQuery, jQuery UI, and additional plugins to be included on the page. I'm aware of the noConflict function, but I have concerns about potential conflicts if ot ...

Validating dates in TypeScript

Currently, I am studying date handling and have an object that contains both a start and end date. For example: Startdate = "2019-12-05" and Enddate = "2020-05-20" My goal is to establish a condition that first verifies the dates are not empty. After tha ...

Error: 'require' is not recognized in index.html file for electron-forge application using the react template

After initiating an electron-forge app using the react template, I encountered an issue where the app only displayed a white screen. The developer console showed the error "Uncaught ReferenceError: require is not defined" at index.html:inline_0.js:2 electr ...

Exploring the Methods to Filter JSON Data in Node.js

There have been significant changes in technologies over the past couple of years since I last checked answers to this question. Currently, I am dealing with JSON files that are being transmitted from a database to my server. My main concern is how to eff ...

When making an Ajax request to another website, the response received is in HTML format instead of

I am attempting to retrieve an array by making an AJAX GET request to a URL. Below is my controller code, which is hosted locally at localhost:3000 def merchant_ids merchants = Merchant.where(id: params[:id]).pluck(:merchant_name, :id, :merchant_city, ...

Transforming an ordinary JavaScript object into a class instance

As I was delving into Angular's documentation on "Interacting with backend services using HTTP", I came across the following statement in the "Requesting a typed response" section: ...because the response is a plain object that cannot be automatical ...

What is the best way to integrate Azure AD authentication into a project using Vue JS and .Net Core Web API?

I'm feeling a bit lost on the implementation of authentication with Azure AD in my app, specifically 'where' to do it within the layers. Currently, I have a Vue JS front end and have come across using ADAL JS for client-side authentication. ...

Exploring the concept of self in JavaScript

Exploring the concept of "self" magic, take a peek at this excerpt from nodejs (which is not complete). Socket.prototype.connect = function(options, cb) { ...... var self = this; var pipe = !!options.path; if (this.destroyed || !this._handle) { ...

What is the best way to transform Vue JS templates into clean HTML code?

Hello, I've received a request to convert a full VueJS template into pure HTML for use in Angular. While I have access to all of Vue's files and codebase, I'm wondering if there's a fast method to convert these templates into standard ...

Issue: Unable to open port (GetCommState) : Error code 1 not recognized - Utilizing Nodejs, express, SerialPort

I am currently attempting to establish a connection between a fiscal printer with serial input and nodejs. I am utilizing the SerialPort module, but encountering difficulty in establishing the connection. The console is displaying the following error messa ...