0

I have this clickable div in a component which fires a todo function when the div is clicked:

<div @click="todo()"></div>

Also, I have a global variable in the component which is called price.

I need to make the div above clickable, or the todo function firable only if the price value is greater than 100.

How can I achieve this behavior in Vue?

1
  • Does the todo() function have access to the global variable price? maybe try <div @click=`${price > 100 ? 'todo()' : ''}`></div> I have no experience with vue by the way.... Commented Feb 4, 2021 at 21:31

2 Answers 2

1

I guess you can simply write a wrapper function like so:

<template>
  <div @click="onClick"></div>
</template>

<script>
export default {
  name: 'MyComponent',
  data() {
    return {
      price: 0
    }
  },
  computed: {
    isTodoCallAllowed() {
      return this.price > 100;
    }
  },
  methods: {
    onClick() {
      if(this.isTodoCallAllowed) {
        this.todo();
      }
    },
    todo() {
      //
    }
  }
}
</script>

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

Comments

0

In general, making divs clickable is usually bad practice, since it can make your interface really unclear and confusing to users.

With this in mind, I think it's easier if you replace your div with a button element, since buttons allow you to use the disabled property to prevent clicks:

new Vue({
  el: '#app',
  data() {
    return {
      price: 100
    }
  },
  computed: {
    priceIsOver() {
      return this.price > 100;
    }
  },
  methods: {
    todo() {
      console.log('doing stuff');
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>

<div id="app">
  <div>
    Price: {{price}} <button @click="price++">+</button> <button @click="price--">-</button>
  </div>
  <br>
  <button :disabled="!priceIsOver" @click="todo">TODO</button>
</div>

Comments

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.