在Vue中重写此JavaScript单击事件时遇到问题
我有一小段JavaScript代码,用于切换repsonsive导航菜单在Vue中重写此JavaScript单击事件时遇到问题,javascript,vue.js,Javascript,Vue.js,我有一小段JavaScript代码,用于切换repsonsive导航菜单 const toggleNavigation = document.getElementsByClassName('navigation-icon')[0] const navbarLinks = document.getElementsByClassName('navbar-links')[0] toggleNavigation.addEventListener('click', () => { navbarLi
const toggleNavigation = document.getElementsByClassName('navigation-icon')[0]
const navbarLinks = document.getElementsByClassName('navbar-links')[0]
toggleNavigation.addEventListener('click', () => {
navbarLinks.classList.toggle('active')
})
我想为Vue重写这个。我以前在Vue中做过事件处理,但我很难将指南中的示例与这段特定代码联系起来
我尝试的是使用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>
导出默认值{
设置(){
const toggleNavigation=document.getElementsByClassName('navigation-icon')[0]
const navbarLinks=document.getElementsByClassName('navbar-links')[0]
如果(toggleNavigation)(=>{
navbarLinks.classList.toggle('active')
}
返回{
航空业,
导航条链接
}
}
}
正确的编写方法是什么?在您的情况下,
toggleNavigation
不是一个函数,因此编写:@click=“toggleNavigation”
请查看Vue.js V3文档中的
处理事件参考:您可以执行以下操作:
<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>
<template>
<ChildComponent @toggled="toggled" />
</template>
<script>
export default {
methods: {
toggled() {
// Handle the toggle logic here
}
}
}
</script>
在父组件中,捕获发出的事件,如下所示:
<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>
<template>
<ChildComponent @toggled="toggled" />
</template>
<script>
export default {
methods: {
toggled() {
// Handle the toggle logic here
}
}
}
</script>
导出默认值{
方法:{
切换(){
//在这里处理切换逻辑
}
}
}
仅供参考:您也可以选择在发射时传递可选参数,只需按如下方式添加它们:this.$emit('toggled',param1,param2)
您可以参考vue3文档来处理事件: