vue2.0中v-on绑定自定义事件

vue中父组件通过prop传递数据给子组件,而想要将子组件的数据传递给父组件,则可以通过自定义事件的绑定。

每个Vue实例都实现了【事件接口】,即:

1、使用 $on(eventName) 监听事件

2、使用 $emit(eventName) 触发事件

父组件可以在使用子组件的地方直接用 v-on 来监听子组件触发的事件。

html代码

<div >
    <my-component  v-on:addpar="priceAll"  v-for="item in mes"  :name="item.name"  :price="item.price"></my-component>
    合计{{all}}
</div>

注册组件

Vue.component('my-component',{
    props: ['name', 'price'],
    template: '<p>名称:{{name}}  单价:{{price}}  <input  value="点击"  type="button"  @click="add">  数量:{{num}}</p>',
    data:function(){
        return{
            num:0
        }
    },
    methods:{
        "add": function(){
            this.num++;
            this.$emit('addpar');
        }
    }
});

创建Vue实例

var con = new Vue({
    el: '#container',
    data:{
        mes: [
            { name:'电脑', price:300 },
            { name:'手机', price:2000 },
            { name:'鼠标', price:500 }
        ],
        all: 0
    },
    methods:{
        priceAll:function() {
            this.all = 0;
            for(let i=0; i<this.$children.length; i++) {
                this.all += this.$children[i].price * this.$children[i].num;
            }
            console.log(this.all)
        }
    }
});

  这个例子是一个极简版的购物车合计,实现的功能是商品数量只要增加就合计一次总金额。

  ① 子组件上绑定有一个click事件,每点击一次数量都会+1;

  ② 为了总金额也改变,通过 v-on 来监听子组件的事件发生,用 $emit 触发了实例中的方法来改变总金额,需要的话方法中可带参数;

  ③ 用 $children 找到了子组件中的数据