一、每个 Vue 实例都实现了事件接口
即:
1、使用 $on(eventName) 监听事件
2、使用 $emit(eventName, optionalPayload) 触发事件
二、注意事项
1、父组件可以在使用子组件的地方直接用 v-on 来监听子组件触发的事件
2、不能用 $on 监听子组件释放的事件,而必须在模板里直接用 v-on 绑定
三、例子及说明
1、父组件代码及说明
<template> ? <div> ? ? <p>{{ total }}</p> ? ? <my-button4 @increment1="incrementTotal1"></my-button4> ? ? <!--自定义方法increment1监听子组件触发情况--> ? ? <my-button4 @increment2="incrementTotal2"></my-button4> ? ? <!--自定义方法increment2监听子组件触发情况--> ? </div> </template> <script> ? import myButton4 from './components/myButton4.vue' ? export default{ ? ? data(){ ? ? ? return{ ? ? ? ? ? total:0 ? ? ? } ? ? }, ? ? methods:{ ? ? ? incrementTotal1: function () { ? ? ? ? ? ? ? ? ? ? /*事件incrementTotal触发*/ ? ? ? ? this.total += 1 ? ? ? }, ? ? ? incrementTotal2: function () { ? ? ? ? ? ? ? ? ? ?/*事件incrementTota2触发*/ ? ? ? ? this.total += 2 ? ? ? } ? ? }, ? ? components:{ ? ? ? ? ? ? ? ? ? ? ? ?/*子组件的实例,要尽量放在最后,不然会出现一些不必要的问题*/ ? ? ? myButton4 ? ? } ? } </script>
2、子组件代码及说明
<template> ? ? ? <button @click="incrementCounter">{{counter}}</button> <!--在子组件中创建一个按钮,创建点击事件--> </template> <script> ? ?export default{ ? ? ?data(){ ? ? ? ?return{ ? ? ? ? ?counter: 0 ? ? ? ?} ? ? ?}, ? ? ?methods: { ? ? ? ?incrementCounter: function (){ ? ? ? ? ?this.counter += 1 ? ? ? ? ?this.$emit('increment1') ? ? ? ?/*触发自定义事件increment1,也就是父组件中的incrementTotal1事件*/ ? ? ? ? ?this.$emit('increment2') ? ? ? ?/*触发自定义事件increment2,也就是父组件中的incrementTotal2事件*/ ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?/*这两个事件一次只会触发一个,为什么呢?很简单,因为每次只单击一个按钮*/ ? ? ? ?} ? ? ?} ? ?} </script>
3、运行截图
A、开始截图:
B、点击第一个按钮截图(+1)
C、点击第二个按钮截图(+2)
四、总说明
1、首先看子组件件,按钮中给其绑定了方法:incrementCounter;
2、点击button时会执行函数 incrementCounter,increment中有 this.$emit(‘increment1)和this.$emit(‘increment2),看点击的是哪个按钮就执行哪个;
3、当incrementCounter执行时,就会触发自定函数increment1(点击第一个按钮的时候)或者increment(点击第二个按钮的时候),也就是incrementTotal1或者incrementTotal2函数;
到此这篇关于关于vue.js中this.$emit的理解使用的文章就介绍到这了,更多相关vue.js this.$emit内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
查看更多关于关于vue.js中this.$emit的理解使用的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did121956