[Vuejs]-How to target body tag to close the side Navbar clicking any where on the screen using Vue?

0👍

I’m not the most fluent in Vue.js, but could you not register an event handler on the body in a lifecycle method?

function closeNavIfOpen () {
  console.log('do your thing')
}
var app = new Vue({
  el: '#app',
  data: {
    message: 'Click anywhere in the body!'
  },
  mounted () {
    window.document.body.addEventListener('click', closeNavIfOpen, false)
  },
  destroyed () {
    window.document.body.removeEventListener('click', closeNavIfOpen, false)
  }
})
body {
  margin: 0;
  min-height: 100vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  {{ message }}
</div>

Leave a comment