Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically add event based on a variable?

Tags:

vue.js

vuejs2

So I'd like to programmatically add an event, e.g. @click depending if on another variable. I can't really use a ref to do something like this.$refs.example.addEventListner("click", someFunction) because I'm doing it for a v-for

I've tried doing something like @click="clickable ? clicked : null" but the function isn't bound even when clickable is true

<template>
  <div id="app">
    <div class="main" @click="clickable ? clicked : null">
    </div>
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld";

export default {
  name: "App",
  data() {
    return {
      clickable: false
    };
  },
  methods: {
    clicked() {
      console.log("clicked");
    }
  },
  components: {
    HelloWorld
  }
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
.main {
  background-color: yellow;
  height: 200px;
  width: 400px;
}
</style>

https://codesandbox.io/s/m941978v9x

like image 754
A. L Avatar asked Mar 03 '26 00:03

A. L


1 Answers

Adding () would allow it to be executed.

@click="clickable ? clicked() : null"

https://codesandbox.io/s/p9l4ozx60x


For more complex conditional statements, you could filter the method using computed.

Demo https://codesandbox.io/s/wnv6kjq2wk

<div class="main" @click="clickedMaybe">
</div>

and

  computed:{
    clickedMaybe(){
      if(this.clickable) return this.clicked;
      return function(){};
    }
  },
like image 126
Jacob Goh Avatar answered Mar 04 '26 13:03

Jacob Goh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!