dmikester1
dmikester1

Reputation: 1382

Vue.js - how to properly conditionally set click handler code

Currently, I have a modal that pops up with a button on it. Depending on some data coming down, I am changing the text and functionality of the button on the modal. I am using a computed to change the button text and another computed to change the button @click code. If the condition is true, it sets the button's @click code to another javascript method.

I'm finding that as soon the modal gets opened, that function that is supposed to be getting attached to the @click of the button is actually getting called and run. Obviously, this is not what I want.

Vue component HTML code:

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

Vue component 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;
  },

Also, the vm.close does seem to be getting properly attached as that only runs when the button is clicked.

Upvotes: 0

Views: 1909

Answers (1)

bbsimonbb
bbsimonbb

Reputation: 29020

Please don't do that ! Vue wants you to separate state from code from markup. If you change the event listener conditionally, you've got a little bit of state living in the markup. @click should just point to a method, and all the conditional logic should be in the method. Just use if() inside your handler in the methods block to differentiate the two cases. It will be much easier to follow.

The thing about computed is that you don't know/shouldn't care when it runs. I suppose you could get into returning a function from a computed, using bind() to link the arguments, but I recoil in horror. I can't see why it has to be so complex.

Upvotes: 3

Related Questions