vue:父子组件prop传值

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
            }
        }

进行事件的切换

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值