0

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.

1
  • 1
    Vue does a pretty good job with this bindinds so please forget about angular trick vm = this. You do not need that. Commented Feb 1, 2019 at 14:57

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hah, thanks for the correction! Helps to have someone else that knows this stuff a little better look at it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.