programing

Vuejs:는 요소를 숨기기.Vuejs:는 요소를 숨기기.keyup 답변?

goodcopy 2022. 8. 30. 23:57
반응형

Vuejs:는 요소를 숨기기.
keyup 답변?

뷰 2.5를 사용하여 나는 그 구성 요소를 숨기려고 하고 있어요.esc키를 누르면.

키자 지정 한정자의 문서에서 영감을 받아, 나는 하지만 영향을 미치지 않(그 순간을 나는, 메시지를 표시하는 덮어 주지 않아요):아래 코드를 썼습니다.

Vue.component('my-component', {
    data: function () {
    return {isVisible:true,
    message:'no key pressed'}
  },
  template: '<div v-on:keyup.esc="myMethod" v-if="isVisible">This is my component<div>{{message}}</div>',
  methods:{
    myMethod : function(){
    this.message = 'esc key pressed'
    //My hiding action...
    }
  }
})

new Vue({
  el: '#app',
  data: {
  }
})

피들

편집: 같은 문제는 사실 저는 정규적인 얼간이 아니라 입력 등 평소에 사용하는 것에 이런 절차를 구현하고 있습니다에 관련된처럼 보인다.

나는 네가 추가해야 할 것 같다.

created: function() {
  document.addEventListener('keyup', this.myMethod);
}

그리고 네 방법:

myMethod(event) {
  if (event.keyCode === 27) {
    this.message = 'esc key pressed'
    console.log('esc key pressed');
  }
}

여기 일하는 것은 예를 들면:https://jsfiddle.net/uzxugzo7/9/.

또한, 파괴하려는, 메모리 누수를 막는 것을 잊지 마세요.

destroyed: function() {
  document.removeEventListener('keyup', this.myMethod);
}

정적 요소 keyboard 이벤트 사용 tabindex 이용할 수 있도록 하려면.

<div v-on:keyup.esc="myMethod" tabindex="0" v-if="isVisible">This is my component<div>{{message}}</div>

나는 같은 것을 사용할 것입니다.

mounted() {
  window.addEventListener('keyup', ev => {
    if (ev.keyCode === 27) {
      * Note keyCode 27 is ESC
      // do stuff here
    }
  })
}

응용 프로그램은 때마다 탈출 열쇠 어디서나 웹 페이지 안에 누르면을 검색하려면 가정하면 응용 프로그램에( 아니라 구성 요소) eventlistener을 첨가한다.mounted(지 않created). 시위의 목적을 위해, 나는을 사용했다.event bus컴포넌트가 수신하는 방법을 보여줍니다.escape-key-pressed이벤트입니다.

(이 스니펫을 테스트하려면 먼저 출력 창을 클릭하십시오.)

Vue.component('custom-component', {
  template: `
    <div>
      <div v-show="show">
        Hide when Escape Key is pressed.
      </div>
      <button v-on:click="reset()">Reset</button>
    </div>`,
  data() {
    return {
      show: true
    }
  },
  created() {
    window.eventBus.$on('escape-key-pressed', (val) => {
      this.show = false
      alert("escape key is pressed")
    })
  },
  methods: {
    reset() { this.show = true }
  }
});

window.eventBus = new Vue({})

const app = new Vue({
  el: "#app",
  mounted() {
    window.addEventListener('keyup', this.handler);    
  },
  destroyed() {
    window.removeEventListener('keyup', this.handler)
  },
  methods: {
    handler() {
      // If escape key is pressed...
      if (event.keyCode == 27) { 
        window.eventBus.$emit('escape-key-pressed', true);
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="app">
   Example
   <custom-component></custom-component>
</div>

언급URL : https://stackoverflow.com/questions/49170123/vuejs-how-to-hide-a-component-div-on-keyup-escape

반응형