Vue2.0 子组件之间通过父组件通信
程序员文章站
2024-03-11 16:32:07
...
子组件1
<script type="text/ecmascript-6">
import Vue from 'vue'
export default {
...
methods: {
addCart(event) {
...
// 分发事件
this.$emit('cart-control', event)
},
...
}
}
</script>
父组件
html
<div class="cartcontrol-wrapper">
<!--监听子组件分发的事件-->
<cartcontrol @cart-control="_drop" :food="food"></cartcontrol>
</div>
js
<script type="text/ecmascript-6">
import support from '@/components/support/support'
import shopcart from '@/componentsopcartopcart'
import cartcontrol from '@/components/cartcontrol/cartcontrol'
import BScroll from 'better-scroll'
const ERROR_OK = 0
export default {
methods: {
_drop(target) {
// 调用子组件(购物车)的drop方法
this.$refs.shopcart.drop(target)
}
},
}
</script>
子组件2
<script type="text/ecmascript-6">
export default {
methods: {
drop(el) {
// 父组件触发的方法
console.log(el)
}
}
}
</script>