如何用自定义事件进行vue组件通讯
import event from '地址'
// 绑定自定义事件
event.$on('handleAddCart', this.handleAddCart)
// 及时销毁,否则可能造成内存泄露
event.$off('handleAddCart', this.handleAddCart)
// 调用自定义事件
event.$emit('handleAddCart', item.id)
下边是具体事例代码
<template>
<div class="wrapper">
<div class="title">
<div>购物车</div>
<div>x</div>
</div>
<ProductList :productList="productList"></ProductList>
<ShoppingCart @add="handleAdd" @emit="handleReduce" :productList="productList" :cartList="cartList"></ShoppingCart>
</div>
</template>
<script>
import event from './event'
import ProductList from './components/ProductList'
import ShoppingCart from './components/ShoppingCart'
export default {
components: {
ProductList,
ShoppingCart
},
data () {
return {
productList: [
{
id: 1,
name: '商品1',
price: 10
},
{
id: 2,
name: '商品2',
price: 15
},
{
id: 3,
name: '商品3',
price: 20
}
],
cartList: [
{
id: 1,
quantity: 1
}
] // 购物车列表数据
}
},
methods: {
// 加入购物车
handleAddCart (id) {
const pro = this.cartList.find((i) => {
return i.id === id
})
if (pro) {
pro.quantity++
return
}
this.cartList.push({
id,
quantity: 1
})
},
// 减少
handleReduce (item) {
const pro = this.cartList.find((i) => {
return i.id === item.id
})
pro.quantity--
// 如果减少到了0
if (pro.quantity <= 0) {
this.cartList = this.cartList.filter(i => {
return i.id !== item.id
})
}
},
// 增加
handleAdd (item) {
const pro = this.cartList.find((i) => {
return i.id === item.id
})
pro.quantity++
}
},
mounted () {
// 绑定自定义事件
event.$on('handleAddCart', this.handleAddCart)
},
beforeDestroy () {
// 及时销毁,否则可能造成内存泄露
event.$off('handleAddCart', this.handleAddCart)
}
}
</script>