doina

一个小菜鸟运维工程师.

Vue 兄弟组件通信

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>

  <div id='app'>
    <h4>父组件</h4>
    <button @click='delEvent'>销毁事件</button>
    <cpn1></cpn1>
    <cpn2></cpn2>
  </div>

  <template id='cpn1'>
    <div>
      <p>cpn1: {{num}}</p>
      <button @click='biuCpn1'>发送事件给组件2</button>
    </div>
  </template>

  <template id='cpn2'>
    <div>
      <p>cpn2: {{num}}</p>
      <button @click='biuCpn2'>发送事件给组件1</button>
    </div>
  </template>

  <script src='../js/vue.v2.6.12.js'></script>
  <script>

    // 点击摧毁事件, 所有事件都会失效
    // 点击组件1中的按钮, 组件2中的num + 2
    // 点击组件2中的按钮, 组件1中的num + 1

    // 定义一个新的实例(事件中心), 用于接收子组件提交的事件
    const cpnBus = new Vue()

    // 发送事件,监听事件和销毁事件
    // cpnBus.$emit('eventName', 'value')
    // cpnBus.$on('eventName', 'value')
    // cpnBus.$off('eventName')

    // 定义组件1
    const cpn1 = Vue.component('cpn1', {
      template: '#cpn1',
      // 定义num, 默认为0
      data() {
        return {
          num: 0,
        };
      },
      // 监听点击, 点击后发送'cpn1-num'事件到事件总线
      methods: {
        biuCpn1() {
          cpnBus.$emit('cpn1-num')
        },
      },
      // 生命周期函数, 模板挂载后, 监听事件总线中的cpn2-num事件,监听到后num + 1
      mounted() {
        cpnBus.$on('cpn2-num', () => {
          this.num += 1
        })
      }
    });

    // 定义组件2
    const cpn2 = Vue.component('cpn2', {
      template: '#cpn2',
      // 定义num, 默认为0
      data() {
        return {
          num: 0,
        };
      },
      // 监听点击, 点击后发送'cpn2-num'事件到事件总线
      methods: {
        biuCpn2() {
          cpnBus.$emit('cpn2-num')
        },
      },
      // 生命周期函数, 模板挂载后, 监听事件总线中的cpn1-num事件,监听到后num + 2
      mounted() {
        cpnBus.$on('cpn1-num', () => {
          this.num += 2
        })
      },
    });

    const app = new Vue({
      el: '#app',
      data: {
        message: 'lylm'
      },
      methods: {
        // 监听点击后, 摧毁事件
        delEvent() {
          cpnBus.$off('cpn1-num')
          cpnBus.$off('cpn2-num')
        }
      }
    })
  </script>
</body>
</html>
点赞

发表评论

邮箱地址不会被公开。

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据