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

 

1、自定义事件 

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

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

<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>

2、使用v-model

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

      尽管Vue允许子组件去修改父组件数据,但在业务中,子组件应该尽量避免依赖父组件的数据,更不应该去主动修改它的数据,因为这样使得父子组件紧耦合,只看父组件,很难理解父组件的状态,因为它可能被任意组件修改,理想情况下,只有组件自己能修改它的状态。父子组件最好还是通过props和$emit来通信。


 

猜你喜欢

转载自blog.csdn.net/u013089490/article/details/83892458