开关灯小案例(兄弟组件通讯)

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    /* 容器 */

    .container {
      width: 150px;
    }

    /* 灯 */

    .light {
      width: 100px;
      height: 100px;
      border-radius: 50%;
      text-align: center;
      line-height: 100px;
      margin: 0 auto;
      color: #fff;
      background-color: #000;
    }

    /* 开灯 */

    .turn-on {
      background-color: #ff0;
      color: #000;
    }

    /* 灯座 */

    .bottom {
      width: 150px;
      height: 50px;
      margin-top: 10px;
      line-height: 50px;
      text-align: center;
      color: #fff;
      background-color: #000;
    }
  </style>
</head>

<body>
  <div id="app" class="container">
    <light-head></light-head>
    <light-bottom></light-bottom>
  </div>
  <script src="./vue.js"></script>
  <script>
    // 1 创建bus
    const bus = new Vue()

    // light-bottom 发送数据    - 触发事件
    // light-head   接受数据    - 注册事件

    Vue.component('light-head', {
      template: `
        <div class="light" :class="{ 'turn-on': isOn }">
          我是一盏灯
        </div>
      `,

      data() {
        return {
          isOn: false
        }
      },

      created() {
        // 注册事件
        bus.$on('light', (data) => {
          this.isOn = data
        })
      }
    })

    Vue.component('light-bottom', {
      template: `
        <div class="bottom">
          <button @click="turnOn(true)">开</button>
          <button @click="turnOn(false)">关</button>
        </div>
      `,

      methods: {
        turnOn(data) {
          // 触发事件
          bus.$emit('light', data)
        }
      }
    })

    var vm = new Vue({
      el: '#app',
      data: {

      }
    })
  </script>
</body>

</html>
posted @ 2019-03-14 10:26  木石天涯  阅读(434)  评论(0编辑  收藏  举报