I am facing an issue with my Vue JS code. When I click on the account <a>
tag, it triggers the toggle
method. The toggle method adds an event listener to the document. However, as soon as the toggle method is executed, the event listener fires and runs the close
function even though the event has already occurred. I'm puzzled as to why this happens and how can I prevent the event from running immediately after the toggle is executed. It should only be triggered on subsequent clicks after the initial one on the <a>
tag.
<template>
<div>
<a v-on:click="this.toggle">Account</a>
<nav v-if="this.open">
<a>Profile</a>
<a>Settings</a>
<a>Sign Out</a>
<a>Admin</a>
</nav>
</div>
</template>
<script lang='ts'>
import { Vue } from 'vue-property-decorator'
export default Vue.extend({
data: function () {
return {
open: false
}
},
methods: {
toggle: function () {
this.open = !this.open
if (this.open) {
// Add click listener to whole page to close dropdown
document.addEventListener('click', this.close)
}
},
close: function () {
console.log('test')
this.open = false;
document.removeEventListener('click', this.close)
}
}
})
</script>