• vue父子组件通信


    Vue父子组件通信

    一、父组件 => 子组件
    1. 父组件向子组件传递值

    通过props传递属性。

    2. 父组件调用子组件

    比如某父组件中有个子组件vue-pager,然后现在要点击父组件中的一个按钮,调用子组件中的方法。
    需要在父组件模板中,用ref标记子组件,然后用this.$refs.[name].[method]调用即可。
    父组件:

    <template>
    <!-- pager -->
    <div>
          <button @click="clickEvent">btn</button>
          <vue-pager :pagerData="pagerDataOfDrug"
                     :condtion="pagerCondtion"
                     ref="vuePager">
          </vue-pager> <!-- /.pager -->
    </div>
    </template>
    
    <script>
    export default {
          methods:
          {
                clickEvent()
                {
                      // console.log(this.$refs.vuePager);
                      this.$refs.vuePager.childMethod();
                }
          }
    }
    </script>
    

    子组件:

    childMethod()
    {
    }
    
    二、子组件 => 父组件
    1. 通过$on $emit做事件监听与触发
    • 通过 $on(eventName) 监听事件
    • 通过 $emit(eventName) 触发事件

    父组件模板:

    <div id="counter-event-example">
      <p>{{ total }}</p>
      <button-counter v-on:increment="incrementTotal($event)"></button-counter>
      <button-counter v-on:increment="incrementTotal($event)"></button-counter>
    </div>
    

    父组件

    new Vue({
      el: '#counter-event-example',
      data: {
        total: 0
      },
      methods: {
        incrementTotal: function (data) {
          this.total += data.count;
        }
      }
    })
    

    子组件

    Vue.component('button-counter', {
      template: '<button v-on:click="increment">{{ counter }}</button>',
      data: function () {
        return {
          counter: 0
        }
      },
      methods: {
        increment: function () {
          const step = 1;
          this.counter += step;
          this.$emit('increment', { count: step });
        }
      },
    })
    

    0c8157590761ff1759cfbc404be3e134.gif

    从 2.3.0 起我们重新引入了 .sync 修饰符,但是这次它只是作为一个编译时的语法糖存在。它会被扩展为一个自动更新父组件属性的 v-on 侦听器。sync-修饰符

    2. 通过$parent直接调用父组件

    子组件 this.$parent[parent method(param)],将值作为参数传入,父组件方法直接使用。

    The end... Last updated by: Jehorn, April 19, 2019, 4:52 PM

  • 相关阅读:
    Android轩辕剑之ActionBar之三
    Android轩辕剑之ActionBar之二
    Android轩辕剑之ActionBar之一
    使用Android OpenGL ES 2.0绘图之六:响应触摸事件
    使用Android OpenGL ES 2.0绘图之五:添加运动
    使用Android OpenGL ES 2.0绘图之四:应用投影和相机视口
    使用Android OpenGL ES 2.0绘图之三:绘制形状
    使用Android OpenGL ES 2.0绘图之二:定义形状
    随笔编号-16 MySQL查看表及索引大小方法
    随笔编号-14 数据库连接最大数问题
  • 原文地址:https://www.cnblogs.com/jehorn/p/7744052.html
Copyright © 2020-2023  润新知