如何用自定义事件进行vue组件通讯
如何自定义事件vue
·
如何用自定义事件进行vue组件通讯
绑定自定义事件并销毁截图 !!! 要及时销毁,避免内存泄露
调用自定义事件截图
下边是示例代码
<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
})
}
},
mounted () {
// 绑定自定义事件
event.$on('handleAddCart', this.handleAddCart)
},
beforeDestroy () {
// 及时销毁,否则可能造成内存泄露
event.$off('handleAddCart', this.handleAddCart)
}
}
</script>
<template>
<div>
<ul>
<li class="items" v-for="item in productList" :key="item.id">
<div>{{item.name}} - {{item.price}}元</div>
<a href="javascript:;" @click="addCart(item)">加入购物车</a>
</li>
</ul>
</div>
</template>
<script>
import event from './../event'
export default {
name: 'ProductList',
props: {
productList: {
type: Array
}
},
data () {
return {
}
},
methods: {
addCart (item) {
// 调用自定义事件
event.$emit('handleAddCart', item.id)
}
}
}
</script>
<style scoped>
@import './../common.css'
</style>
---------------------------------------------------------------------------------------------
上边的写的不是很容易看出来,下边写个容易的 vue自定义事件
首先 myInput 和 List是两个相邻的组件,在List组件想要获取到 myInput组件的title值,如下截图
---------- end ----
更多推荐
已为社区贡献2条内容
所有评论(0)