itsource

변수를 기반으로 이벤트를 프로그래밍 방식으로 추가하려면 어떻게 해야 합니까?

mycopycode 2022. 8. 29. 22:24
반응형

변수를 기반으로 이벤트를 프로그래밍 방식으로 추가하려면 어떻게 해야 합니까?

이벤트를 프로그래밍 방식으로 추가하려고 합니다.@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

반응형