vue:父子组件prop传值
前言
使用prop传值复用组件,在商城项目中,对商品联动菜单进行复用,之前学习使用中,看别人使用的是通过路由信息进行判断,于是我决定用prop进行v-show判断
prop使用
子组件
<div @mouseleave="leaveIndex" @mouseenter="showTrue" >
<h2 class="all">全部商品分类</h2>
<div class="sort" v-show="show"></div>
</div>
<script>
// 通过prop实现商品分类菜单的显示与隐藏
export default {
name:'index'
props: {
// 初始值为true,正常情况下显示
show: {
type: Boolean,
default: true
}
},
methods:{
leaveIndex() {
// 接受父组件方法,隐藏商品分类,绑定父组件的mouseleave方法
this.$emit('mouseleave')
},
// 接受父组件方法,显示商品分类绑定父组件的mouseenter方法
showTrue(){
this.$emit('mouseenter')
}
}
}
</script>
父组件
<div>
<!--prop父子传值,方法调用是data中的show切换-->
<typeNav :show="show" @mouseenter="showCaidan" @mouseleave="noShowCaidan"/>
</div>
<script>
export default {
name: "index",
data() {
return {
show: false// 商品分类菜单的显示隐藏
}
},
methods: {
// 显示菜单的方法,@mouseenter 鼠标移入,show切换为true
showCaidan() {
this.show = true
},
// 隐藏菜单,移除隐藏
noShowCaidan() {
this.show = false
}
}
}
</script>
总结
`
在子组件声明prop初始值为布尔与true,通过过父组件声明鼠标事件:
<typeNav :show="show" @mouseenter="showCaidan" @mouseleave="noShowCaidan"/>
子组件绑定父组件的事件:
methods:{
leaveIndex() {
// 接受父组件方法,隐藏商品分类,绑定父组件的mouseleave方法
this.$emit('mouseleave')
},
// 接受父组件方法,显示商品分类绑定父组件的mouseenter方法
showTrue(){
this.$emit('mouseenter')
}
}
就可以通过父组件中的事件判断
methods: {
// 显示菜单的方法,@mouseenter 鼠标移入,show切换为true
showCaidan() {
this.show = true
},
// 隐藏菜单,移除隐藏
noShowCaidan() {
this.show = false
}
}
进行事件的切换