vue父子组件通信 Vue父子组件通信

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 >
  <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 });
    }
  },
})

vue父子组件通信
Vue父子组件通信

从 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