vue-组件子传父(事件机制)

  • a.使用 $on(eventName) 监听事件
  • b.使用 $emit(eventName) 触发事件
  • 假设第二层组件想和第一层组件进行通信,分析其传值过程
    (第二层向第一层传值):子组件通过触发自定义事件向父组件传值,如此便实现了父子组件向上通信
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Examples</title>
</head>
<body>
  <div id="box">
    父组件
    <child @myevent2="handleEvent"></child>
  </div>

  <script src="http://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script type="text/javascript">
    //子组件
    Vue.component("child", {
      template: `<div>
          child组件
          <button @click="payMoney()">click</button>
        </div>`,

      data() {
        return {
          childname: "子组件的状态"
        }
      },
      methods: {
        payMoney() {
          //$emit()分发/触发 事件
          this.$emit("myevent2", this.childname)
        }
      }
    })
    
    new Vue({
      el: "#box",
      methods: {
        handleEvent(ev) {
          console.log("父组件收到钱了", ev)
        }
      }
    })
  </script>
</body>
</html>

案例:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Examples</title>
</head>
<body>
    <div id="box">
        <!-- <button @click="isShow=!isShow">click</button> -->
        <navbar @myevent="handleEvent"></navbar><!--2-->
        <sidebar v-show="isShow"></sidebar>

    </div>
    <script src="http://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script type="text/javascript">
        //子组件
        Vue.component("navbar", {
            template: `<div>
            navbar      
            <button @click="handleClick">navbar-button</button>
          </div>`,
            methods: {
                handleClick() {
                    this.$emit("myevent")//1
                }
            }
        })

        Vue.component("sidebar", {
            template: `<div style="background:yellow;width:200px;">
            <ul>
              <li>11111</li>  
              <li>11111</li>  
              <li>11111</li>  
            </ul>  
          </div>`
        })

        new Vue({
            el: "#box",
            data: {
                isShow: false
            },
            methods: {  //3
                handleEvent() {
                    this.isShow = !this.isShow
                }
            },
        })
    </script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值