Mastering Vue.js - A guide to effectively implementing conditional click handlers

Currently, I have implemented a modal that appears with a button on it. The text and functionality of the button change based on certain data conditions. To achieve this, I am utilizing computed properties to dynamically alter both the button text and its associated @click code. When a specific condition is met, the @click code is set to call another JavaScript method.

An issue arises where the function intended to be assigned to the button's @click event is automatically triggered as soon as the modal opens, which is not the desired behavior.

Here is the HTML code for the Vue component:

<button
  variant="primary"
  outline
  type="button"
  @click="continueButtonClick"
>
  {{ continueButtonText }}
</button>

And here is the corresponding JS code:

computed: {
  continueButtonClick() {
    let vm = this;
    let click = vm.close;
    console.log("itemMapText: ", vm.item.itemMapText);
    if(vm.item.itemMapText === "map_displayText_viewPriceInCart") {
      click = vm.updateCartVue(vm.item.itemId);
    }
    return click;
  },
  continueButtonText() {
    let vm = this;
    let buttonText = "Continue Shopping";
    if(vm.item.itemMapText === "map_displayText_viewPriceInCart") {
      buttonText = "Remove From Cart";
    }
    return buttonText;
  },

It should be noted that vm.close functions correctly and is only executed upon clicking the button.

Answer №1

It is highly recommended not to do that! Vue strongly encourages separating state, code, and markup. By changing the event listener conditionally, you are introducing a bit of state within the markup itself. Instead, it is advised to have @click point to a method, with all conditional logic residing within that method. Utilize if() statements inside your handler in the methods block to handle different cases, making the code much easier to understand and maintain.

The approach with computed properties is that you shouldn't be concerned about when they run. While it is possible to return a function from a computed property and use bind() to link arguments, this can lead to unnecessary complexity. Keeping things simple and straightforward is often the best practice.

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

Working with JavaScript Arrays as Function Parameters

After reading extensively about passing arrays as function parameters for different return values, I encountered an issue when working with three separate JS files. main.js module.exports = function(){ this.deliver = require('./file1.js') ...

How can I perform a cross-domain XMLHTTPREQUEST to communicate with an FTP server using the appropriate syntax?

I am currently using a webDav CORS plugin to manage files on a webDav server through POST/PUT/GET/REMOVE/ALLDOCS requests. Now, I am attempting to achieve the same functionality for FTP but am facing difficulties with the xmlhttprequest syntax (I keep rec ...

Preventing scrolling on a YouTube video embed

I have been working hard on developing my personal website. One issue I encountered is that when there is a YouTube video embedded in the site, it stops scrolling when I hover over it. I would like the main document to continue scrolling even if the mouse ...

It appears that the Office.EventType.ItemChanged event is not triggering as expected

Currently, I am exploring a simple console.log print test to see how it behaves when I switch from one email to another within Outlook. To guide me through this process, I have been referring to the instructions provided by Microsoft over at this link. In ...

Accessing a specific value from a key in a JavaScript object array

My data structure consists of an associative array indexed by dates, with each element containing another array. [03/16/2015: Array[3], 03/17/2015: Array[3], 03/18/2015: Array[3], 03/19/2015: Array[3]] The array was created using the following code: ar ...

Can anyone explain why I keep encountering an endless loop when using react hooks?

Having a bit of trouble with fetching data from a JS file that is mimicking an API with some endpoint methods. When I console log the data, everything seems fine, but for some reason, I keep running into an infinite loop when using hooks. I've tried t ...

What is the best way to identify the top and bottom row currently visible in a scrollable HTML table using JavaScript and VueJS?

In my HTML table, there is a thead and tbody sections, with an unpredictable number of rows in the tbody based on the array size. This table has a max-height and can be scrolled. I want to be able to accurately calculate the new top and bottom rows displa ...

Exploring the creation of sub routes within components

I'm embarking on a project to create a robust Vue application featuring multiple modules. Imagine, for instance, an online store that requires separate modules for customers, products, stock inventory, orders, and invoices. Each of these modules will ...

Import the complete JSON file into a variable as an array

I am struggling with loading an external json file (locations.json) into a variable and then using the information found here: http://www.json.org/js.html Despite trying various methods, I have not been successful in populating the variable. Even after fo ...

Insert HTML code that is activated when the selection is modified

I have a simple dropdown menu in my HTML code. HTML <select name="breed" onchange="breedChanged()"> <?php while ($row = gdrcd_query($result, 'fetch')){ ?> <option value="<?php echo $row['id_breed']; ?& ...

Having difficulty modifying the styling of a paragraph within a div container

I have been working on a function that is supposed to adjust the font-size and text-align properties of a paragraph located within a div tag once a button is pressed. function customizeText() { document.getElementById('centretext').innerHTML = ...

Is there a way to connect two tables using CSS pseudo-selectors?

Is there a way to make two separate tables interact with each other using CSS pseudo-selectors? I have a data table and an auto-numbered table, and I want the rows to highlight in both tables when hovering over a cell in one of them. I've tried using ...

Using node.js with express to send data stored in a variable to the browser instead of displaying it in the

I'm currently getting the hang of node.js. It's pretty straightforward to use res.send and output some basic "hello world" text, but how can I pass variables to the browser instead of just to the console? Here is a snippet of code: var Tester = ...

Trigger a live event in JavaScript that mimics jQuery's functionality

I have an event on a page that I need to trigger from a Chrome Extension without being able to modify the page's JavaScript directly. $(selector).live("click", fn); In my Chrome extension, I'm trying to achieve this with native JS like so: sel ...

Guide to configuring the initial lookAt/target for a Control

I'm looking to establish the initial 'lookAt' point for my scene, which will serve as both the center of the screen and the rotation control's focus. Ideally, I'd like to set a specific point or object position rather than rotation ...

What is the most effective way to display child elements in a React component without explicitly passing them

I created a component: const PapeConainer = ({children}) => { return ( <div //some classes and other stuff> {children} </div> ); } However, I received a comment on my merge request stating that I don't need to pass chi ...

PHP question about maintaining data continuously

So, I've created this interesting JavaScript 'thing' with the help of jQuery and AJAX. The main concept behind it is that a div can be edited (contenteditable=true), which sparked the idea to develop a chatroom-like feature. It's pretty ...

When a JSON object is handled as a string

The JSON returned from my Ajax call looks like this: returnedData = "[ { id: 1, firstName: 'John', lastName: 'Smith', address: '123 Spa Road', city: 'London', orders: [ { product: ...

Disappear the loading icon once all children have finished rendering

I'm facing a minor issue with rendering in React and struggling to find a solution. Here's what's happening: My component acts as a wrapper for multiple entries, like this: class MyWrapper extends Component { renderItems() { return ( ...

Successfully changing the source and tracking of a video through an onclick button, but the video content remains unchanged

I apologize if this post is a duplicate, but I couldn't find the answer in previous threads. I'm attempting to change the video source using an onclick button. However, even after changing the source, the video remains the same. <video width ...