不二如是 发表于 2018-10-5 11:09:17

029 V 自定义事件

本帖最后由 不二如是 于 2018-10-5 15:00 编辑

https://xxx.ilovefishc.com/forum/201808/24/170823gj1tj61c4apj6o1e.jpg

上一讲我们搞定了数据验证,本次来学习自定义事件。

我们现在已经知道,从父组件向子组件通信,通过props就可以了。

但是Vue组件的通信的应用场景,不止于此,归纳起来如下图所示:


组件关系分为:父子组件通信、兄弟组件通信、跨级组件通信

当子组件需要向父组件传递数据时,就要用到自定义事件。

之前讲过的v-on除了监听DOM事件外,还可以用于组件之间的自定义事件。

父组件可以直接在子组件的自定义标签上使用v-on来监听子组件触发的自定义事件。

创建div:
<div id="myApp">
    <p>总计:{{total}}</p>
    <my-component v-on:increase="handleGetTotal" v-on:reduce="handleGetTotal"></my-component>
</div>

创建组件:
Vue.component('my-component',{
      template:'\
      <div>\
      <button @click="handleIncrease">+1</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);
            }
      }
    });

创建Vue实例:
var app = new Vue({
      el:"#myApp",
      data:{
            total:0
      },
      methods:{
            handleGetTotal:function(total){
                this.total = total;
            }
      }
    })


子组件中有两个按钮,分别实现+1和-1效果。

在改变组件的data中“counter”后,通过$emit()把它传递给父组件。

父组件用v-on:increase和v-on:reduce。

$emit()方法的第一个参数是自定义事件的名称,例如示例的increase和reduce后面的参数都是要传递的数据。



课后作业


1、父组件可以向子组件通信吗?

2、组件关系分为哪三种?

3、通过v-on父组件可以直接监听子组件触发的自定义事件(T/F)

4、请用语法糖简写下面的代码:
<my-component v-on:increase="handleGetTotal" v-on:reduce="handleGetTotal"></my-component>



答案:
**** Hidden Message *****



如果有收获,别忘了评分{:10_281:} :

http://xxx.fishc.com/forum/201709/19/094516hku92k2g4kefz8ms.gif

这位鱼油,如果喜欢Vue,请订阅 专辑(传送门)(不喜欢更要订阅{:10_297:} )

http://xxx.fishc.com/forum/201803/21/151715umqz1qoywp11wjbq.gif

lbjstudypython 发表于 2018-11-27 20:49:23

1.可以通过props进行通信
2.父子组件通信、兄弟组件通信、跨级组件通信
3.T
4.<my-component @increase="handleGetTotal" @reduce="handleGetTotal"></my-component>

Ruide 发表于 2020-4-10 11:54:43

1.可以
2.父子,兄弟,跨级
3.T
4.
<my-component @:increase="handleGetTotal" @:reduce="handleGetTotal"></my-component>

一笙彤 发表于 2020-6-21 15:50:35

0

jack6666 发表于 2022-11-1 21:33:02

1
页: [1]
查看完整版本: 029 V 自定义事件