Vue通讯组件之四:子组件向父组件传值

一、自定义事件 

     当子组件须要向父组件传递数据时,就要用到自定义事件。Vue的子组件用$emit()来触发事件,父组件用$on()来监听子组件的事件。父组件也能够直接在子组件的自定义标签上使用v-on来监听子组件触发的自定义事件。javascript

使用要求:在子组件中经过$emit()把值传递给父组件,父组件使用v-on:xxx(或者使用语法糖@xxx);可是须要注意$emit()第一个参数是自定义事件的名称。html

子组件内部经过this.$emit('方法名', 要传递的数据)方式,来调用父组件中的方法,同时把数据传递给父组件使用java

<div id="app">
   <p>总数:{{total}} </p>
   <my-component  @increase=”handleGetTotal” @reduce= ”handleGetTotal”></my-component>
</div>
<script>
Vue.component('my-component' {
     template:`\
          <div >\
          <button @cl 工ck= ” handle Increase” > + l </button > \
          <button @click= ” handleReduce ” >- 1 < /button> \
          </div> `,
    data:function () {
            return {
                counter : 0
        },
    methods:{
        handleincrease: function () {
            this.counter++;
            this.$emit ('increase', this.counter);
       },
    handleReduce: function () {
            this.counter--;
            this.$emit('reduce', this.counter);
		}

});
var app =new Vue({
    el :’ #app ’,
    data: {
       total: 0
	}
    methods : {
        handleGetTotal: function (total) {
        this.total = total ;
    })
</script>

 

二、使用v-model

在父组件上使用v-model指令,子组件使用this.$emit('input',this.子组件属性)app

      尽管Vue容许子组件去修改父组件数据,但在业务中,子组件应该尽可能避免依赖父组件的数据,更不该该去主动修改它的数据,由于这样使得父子组件紧耦合,只看父组件,很难理解父组件的状态,由于它可能被任意组件修改,理想状况下,只有组件本身能修改它的状态。父子组件最好仍是经过props和$emit来通讯。this

三、应用功说明

          原理:父组件将方法的引用,传递到子组件内部,子组件在内部调用父组件传递过来的方法,同时把要发送给父组件的数据,在调用方法的时候看成参数传递进去;
          父组件将方法的引用传递给子组件,其中,getMsg是父组件中methods中定义的方法名称,func是子组件调用传递过来方法时候的方法名称。spa

<son @func="getMsg"></son>

子组件内部经过this.$emit('方法名', 要传递的数据)方式,来调用父组件中的方法,同时把数据传递给父组件使用。
 code

<div id="app">
    <!-- 引用父组件 -->
    <son @func="getMsg"></son>

    <!-- 组件模板定义 -->
    <script type="x-template" id="son">
      <div>
        <input type="button" value="向父组件传值" @click="sendMsg" />
      </div>
    </script>
  </div>

  <script>
    // 子组件的定义方式
    Vue.component('son', {
      template: '#son', // 组件模板Id
      methods: {
        sendMsg() { // 按钮的点击事件
          this.$emit('func', 'OK'); // 调用父组件传递过来的方法,同时把数据传递出去
        }
      }
    });

    // 建立 Vue 实例,获得 ViewModel
    var vm = new Vue({
      el: '#app',
      data: {},
      methods: {
        getMsg(val){ // 子组件中,经过 this.$emit() 实际调用的方法,在此进行定义
          alert(val);
        }
      }
    });
  </script>