所以我想以编程方式添加一个事件,例如@click
取决于另一个变量。我不能真正使用 ref 来做类似 this.$refs.example.addEventListner("click", someFunction)
的事情,因为我这样做是为了 v-for
我试过做类似 @clickable ? clicked : null"
的操作,但即使 clickable
为真,该功能也未绑定(bind)
<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>
最佳答案
添加 ()
将允许它执行。
@click="clickable ? clicked() : null"
https://codesandbox.io/s/p9l4ozx60x
对于更复杂的条件语句,您可以使用计算过滤方法。
演示 https://codesandbox.io/s/wnv6kjq2wk
<div class="main" @click="clickedMaybe">
</div>
和
computed:{
clickedMaybe(){
if(this.clickable) return this.clicked;
return function(){};
}
},
关于vue.js - 如何以编程方式添加基于变量的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50208149/