子组件之间的通信:使用从其他组件中的按钮发出来显示/隐藏购物车



我正在使用具有惯性 vue3 和 Laravel 的购物车,页面布局要求有一个带有袋子按钮的主菜单,点击时会触发显示和隐藏购物车事件。 因此,由于菜单和购物车是主页中的子组件,我想目标是通过使用组件之间的通信。 我已经阅读了 emit 文档,我可以让它从父级到子级以及从子级到父级工作,但我无法实现两个子组件之间的通信。

我有以下代码:

父母

<Cart :isVisible="showCart" @hideCart="showCart = false" />
<script>
export default { 
data() {
return {
showCart: false,
}
},
methods: {
toggleCart() {
this.showCart = !this.showCart    
},
}
}
</script>

菜单

<button @click="$emit('toggleCart')"><Icon name="bag" class="w-4" /></button>

<template>
<div v-if="isVisible">
<h3 class="flex justify-between">
<span class="font-bold">My cart</span>
<button @click="$emit('toggleCart')" class="text-xl">&times;</button>
</h3>
...html code for cart
</div>
</template>
<script setup>
import { Link } from "@inertiajs/inertia-vue3";
const props = defineProps(["isVisible", "cart"]);
const emit = defineEmits(["toggleCart"]);
</script>
$emit

不调用父级中的方法,您必须自己处理$emitted事件,通常是通过调用方法。因此,在父组件中,您应该具有:

<template>
<Cart :isVisible="showCart" @toggle-cart="toggleCart"..... />
<Menu @toggle-cart="toggleCart" ..... />
</template>
<script>
//...
methods: {
toggleCart() {
this.showCart = !this.showCart    
},
//...
</script>
@toggle-cart=

引用发出的事件,"toggleCart"引用父组件中的方法,但它们不需要具有相同的名称。只要handleCartToggle是方法名称,就可以@toggle-cart="handleCartToggle"。 (注意:烤肉串大小写@toggle-cart而不是@toggleCart是 Vue 建议您引用模板中的事件的方式,以与 HTML 属性保持一致。仍然在购物车组件中使用toggleCart

最新更新