美文网首页
vue 组件之间通信

vue 组件之间通信

作者: 阿亮2019 | 来源:发表于2018-09-09 16:48 被阅读8次

    一切从简,不用webpack。

    1. props $emit

    主要是父子之间通信,兄弟之间通信。

    <!-- html -->
    <!DOCTYPE html>
    <html>
    <head>
    <script src="http://vuejs.org/js/vue.js"></script>
      <meta charset="utf-8">
      <title>JS Bin</title>
    </head>
    <body>
    <div id="app">
      <p>父组件中的值parentNum: {{ parentNum }}</p>
      <add-component :transfer=parentNum @change=plus></add-component>
      <reset-component @reset=reset></reset-component>
      <button @click=fatherAdd>父组件自增</button>
    </div>
    </body>
    </html>
    
    Vue.component('add-component', {
      template: `
        <div>
          <div>子组件中的值childNum: {{childNum}}</div>
          <button @click="increment">子组件中自增</button>
        </div>
      `,
      props: {
        transfer: {
          Number,
        }
      },
      watch: {
        'transfer': function(childNum) {
          this.childNum = childNum;
        }
      },
      data() {
        console.warn('transfer:' + this.transfer);
        return {
           childNum: this.transfer
        }
      },
              
      methods: {
        increment() {
          this.childNum++;
          this.$emit('change', this.childNum)
        }
      },
    });
    
    Vue.component('reset-component', {
      template: `
        <div>
          <button @click=reset>重置</button>
        </div>
      `,
      methods: {
        reset() {
          this.$emit('reset');
        }
      }
    });
    
    new Vue({
      el: '#app',
      data: {
        parentNum: 0
      },
      methods: {
        fatherAdd() {
          this.parentNum += 1;
        },
        plus(newNum) {
          console.log('newNum:' + newNum);
          this.parentNum = newNum;
        },
        reset() {
          this.parentNum = 0;
        }
      }
    })
    

    父子之间通信说明:
    父组件向子组件add-component传递初始值parentNum,子组件通过props接受并自定内部变量用childNum,子组件中有一个按钮,每点击一下数值就会自增1。

    如果子组件用了自己的变量而不是直接用的父组件的变量,则需要通过watch来实时更新子组件的内容 。
    watch transfer表示: 一旦父组件更新了,立马传递到子组件中。
    子组件通过$emit方法向父组件传递数值。

    兄弟组件通信说明:
    reset-component是add-component的兄弟组件,本示例中无法直接通信,可借助父组件通信。

    2. eventBus

    /新建一个Vue实例作为中央事件总嫌/
    let event = new Vue();

    /监听事件/
    event.$on('eventName', (val) => {
    //......do something
    });

    /触发事件/
    event.$emit('eventName', 'this is a message.');

    相关文章

      网友评论

          本文标题:vue 组件之间通信

          本文链接:https://www.haomeiwen.com/subject/pkhdgftx.html