programing

Vue의 v-on 지시어에 여러 이벤트 바인딩

prostudy 2022. 5. 10. 22:23
반응형

Vue의 v-on 지시어에 여러 이벤트 바인딩

jQuery에서는 다음과 같은 작업을 수행하여 여러 이벤트를 바인딩할 수 있다.

$('#myDiv').on('touchstart mousedown', // more code here

그리고 내가 아는 한 이것은 들을 것이다.touchstartORmousedown동시에하지만 나는 부에와 동등한 것을 어떻게 해야 할지 모르겠어.나는 오직 할 수 있다.@touchstart="doSomething()"또는@mousedown="doSomething()"내가 뭔가 명백한 것을 놓치고 있는 것일까?고마워요.

1. 이벤트 한정자 포함

만약 당신이 의지하고 있다면events, 이벤트 수식어를 바인딩하여 인라인으로 연결시킬 수 있다.다음과 같은 경우:

<a @click.stop="doThis" @click.right="showContextMenu"></a>

2. 프로그래밍 방식으로 이벤트 첨부

또는 이벤트 목록과 각 구현을 작성하여 로 루프를 첨부하고 이 게시물에서 해결 방법을 실행하십시오.

created() {
    const EVENTS = [
      {name: 'my-event1', callback: () => console.log('event1')},
      {name: 'my-event2', callback: () => console.log('event2')},
      {name: 'my-event3', callback: () => console.log('event3')}
    ]

    for (let e of EVENTS) {
      this.$on(e.name, e.callback); // Add event listeners
    }
  }

<button @click="$emit('my-event1')">Raise event1</button>
<button @click="$emit('my-event2')">Raise event2</button>
<button @click="$emit('my-event3')">Raise event3</button>

3. v-on여러 가지 가치관

그렇지 않으면 여러 값에 대해 할 수 있는 것처럼 실제로 같은 작업을 수행할 수 있다.v-on행사용의

<div id="mydDiv" v-on="handlers"></div>

// ...

data() {
  const vm = this;

  return {
    handlers: {
      mousedown: vm.divMousedown,
      touchstart: vm.divTouchstart
    }
  }
},

methods: {
  divMousedown() {
    console.log('event: mousedown');
  },
  divTouchstart() {
    console.log('event: touched');
  }
}

이벤트 유형별로 처리기를 세분화해야 하는 경우 이벤트가 실행되는 동안 다음을 검사해 보십시오.touchstart또한 방아쇠를 당기는 것 같다.mousedown, 아마도:

methods: {
  onTouched(evt) {
    evt.preventDefault();

    if (evt.type === 'mousedown') {
        // handle mousedown
    }
    else if (evt.type === 'touchstart') {
        // ...
    }
  }
}

참고: 전화를 걸어 보십시오.preventDefault()에 관하여touchmove보다는touchstart그렇게 하면, 쥐 이벤트는 여전히 발사될 수 있고 링크와 같은 것들은 계속 작동될 것이다.

아니, 너는 아무것도 놓치고 있지 않아."터치스타트 머즈다운"은 jQuery가 편의를 위해 제공하는 짧은 손 표기법이다.Vue는 유사한 편의성을 제공하지 않는다(아마도, 제공된 모든 옵션으로 이미 이벤트 바인딩 구문이 상당히 복잡해질 수 있기 때문이다).

올바른 방법은 다음과 같은 두 가지 특성을 사용하는 것으로,@touchstart="doSomething()" or @mousedown="doSomething()"

속성 이름에 내재된 제한과 런타임 오버헤드를 방지하려는 욕구로 인해 vue는 여러 이벤트에 바인딩하는 것을 의도적으로 지원하지 않는다.

만약 당신이 반드시 다중 이벤트 바인딩을 가지고 있어야 한다면, 맞춤 지침이 바로 그 방법일 것이다.

(SO가 답변에 코드 없이 안절부절못한 관계로 연결된 JSFiddle에서 다음 코드를 뻔뻔스럽게 복사함)

function functionWrapper(e) {
  /* add filters to handle event type before propagating to callback function for custom event handler */
  e.target.__handler__.fn(e)
}

Vue.directive('multiEvent', {
  bind: function(el, binding, vnode) {
    el.__handler__ = binding.value
    binding.value.evt.forEach(e => el.addEventListener(e, functionWrapper))
  },
  unbind: function(el, binding) {
    el.__handler__.evt.forEach(e => el.removeEventListener(e, functionWrapper))
    el.__handler__ = null
  }
})

사용량:

<input v-multi-event="{ evt: ['click', 'blur', 'change', 'keydown'], fn: someCallback }">

참조URL: https://stackoverflow.com/questions/53825246/bind-multiple-events-to-v-on-directive-in-vue

반응형