반응형
변수를 기반으로 이벤트를 프로그래밍 방식으로 추가하려면 어떻게 해야 합니까?
이벤트를 프로그래밍 방식으로 추가하려고 합니다.@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>
https://codesandbox.io/s/m941978v9x
추가 중()
실행할 수 있습니다.
@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(){};
}
},
이 코드를 사용해 보세요.조건부로 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>
언급URL : https://stackoverflow.com/questions/50208149/how-to-programmatically-add-event-based-on-a-variable
반응형
'itsource' 카테고리의 다른 글
VueJs에서 특정 경로 데이터를 경로 이름으로 가져오려면 어떻게 해야 합니까? (0) | 2022.08.30 |
---|---|
문자열을 UTF-8로 인코딩 (0) | 2022.08.30 |
다른 포트에서 제공되는 Vue 앱과 함께 로컬 API를 사용하는 방법 (0) | 2022.08.29 |
Vue js에서 추적 기준 또는 v-for의 키는 어떤 용도로 사용됩니까? (0) | 2022.08.29 |
타입 스크립트에서 VueJ를 사용하는 방법 (0) | 2022.08.29 |