所以我想以编程方式添加一个事件,例如@click
取决于另一个变量。我无法真正使用引用来执行this.$refs.example.addEventListner("click", someFunction)
之类的操作,因为我正在为v-for
我尝试过像@click="clickable ? clicked : null"
这样的事情,但即使clickable
为真,该函数也没有约束
<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>
答案 0 :(得分:4)
添加()
将允许它被执行。
@click="clickable ? clicked() : null"
https://codesandbox.io/s/p9l4ozx60x
对于更复杂的条件语句,您可以使用computed过滤方法。
演示https://codesandbox.io/s/wnv6kjq2wk
<div class="main" @click="clickedMaybe">
</div>
和
computed:{
clickedMaybe(){
if(this.clickable) return this.clicked;
return function(){};
}
},
答案 1 :(得分:0)
尝试使用此代码,您可以有条件地渲染DOM节点,我尝试了它,它就像魅力一样。
<template>
<div id="app">
<div class="main" v-if="clickable" @click="clicked"></div>
<div class="main" v-if="!clickable"></div>
</div>
</template>
<script>
import HelloWorld from "./components/HelloWorld";
export default {
name: "App",
data() {
return {
clickable: true
};
},
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>