Reputation: 21
I have a small piece of JavaScript code that is used to toggle a repsonsive navigation menu.
const toggleNavigation = document.getElementsByClassName('navigation-icon')[0]
const navbarLinks = document.getElementsByClassName('navbar-links')[0]
toggleNavigation.addEventListener('click', () => {
navbarLinks.classList.toggle('active')
})
I want to rewrite this for Vue. I have done event handling in Vue before, but it is difficult for me to relate the examples in the guide to this particular piece of code.
What I tried was to use the v-on directive:
<template>
<div class="navigation-icon" @click="toggleNavigation">
<i class="pi pi-bars"></i>
</div>
</template>
<script>
export default {
setup() {
const toggleNavigation = document.getElementsByClassName('navigation-icon')[0]
const navbarLinks = document.getElementsByClassName('navbar-links')[0]
if (toggleNavigation) () => {
navbarLinks.classList.toggle('active')
}
return {
toggleNavigation,
navbarLinks
}
}
}
</script>
What is the correct way to write this?
Upvotes: 1
Views: 90
Reputation: 745
You can do something like this:
<template>
<div class="navigation-icon" @click="toggleNavigation">
<i class="pi pi-bars"></i>
</div>
</template>
<script>
export default {
methods: {
toggleNavigation() {
// Handle the toggle logic here
}
}
}
</script>
Now if you want to emit something out of this component to a parent component, use the event emitter inside the toggleNavigation()
method. More on this here.
toggleNavigation() {
this.$emit('toggled')
}
In the parent component, catch the emitted event like this:
<template>
<ChildComponent @toggled="toggled" />
</template>
<script>
export default {
methods: {
toggled() {
// Handle the toggle logic here
}
}
}
</script>
FYI: You can choose to pass optional params too while emitting, just add them like this: this.$emit('toggled', param1, param2)
.
Upvotes: 0
Reputation: 922
In your case toggleNavigation
is not a function, so it make no sense to write: @click="toggleNavigation"
Please take a look at the handling event
reference from the Vue.js V3 docs: https://v3.vuejs.org/guide/events.html#event-handling
Upvotes: 1