[英]I am having issues trying to rewrite this JavaScript click event in Vue
I have a small piece of JavaScript code that is used to toggle a repsonsive navigation menu.我有一小段 JavaScript 代码用于切换响应式导航菜单。
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.我想为 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.
我之前在 Vue 中做过事件处理,但是我很难将指南中的示例与这段特定的代码联系起来。
What I tried was to use the v-on directive:我尝试的是使用 v-on 指令:
<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?写这个的正确方法是什么?
In your case toggleNavigation
is not a function, so it make no sense to write: @click="toggleNavigation"
在您的情况下,
toggleNavigation
不是 function,因此编写没有意义: @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请查看 Vue.js V3 文档中的
handling event
参考: https://v3.vuejs.org/guide/events.html#event-handling
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.现在,如果您想从该组件向父组件发出某些内容,请在
toggleNavigation()
方法中使用事件发射器。 More on this here .更多关于这个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)
.仅供参考:您也可以选择在发射时传递可选参数,只需像这样添加它们:
this.$emit('toggled', param1, param2)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.