经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » Vue.js » 查看文章
关于vue.js中this.$emit的理解使用
来源:jb51  时间:2022/8/22 14:54:52  对本文有异议

一、每个 Vue 实例都实现了事件接口

即:

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

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

二、注意事项

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

 2、不能用 $on 监听子组件释放的事件,而必须在模板里直接用 v-on 绑定

三、例子及说明

1、父组件代码及说明

  1. <template>
  2. ? <div>
  3. ? ? <p>{{ total }}</p>
  4. ? ? <my-button4 @increment1="incrementTotal1"></my-button4> ? ? <!--自定义方法increment1监听子组件触发情况-->
  5. ? ? <my-button4 @increment2="incrementTotal2"></my-button4> ? ? <!--自定义方法increment2监听子组件触发情况-->
  6. ? </div>
  7. </template>
  8.  
  9. <script>
  10. ? import myButton4 from './components/myButton4.vue'
  11. ? export default{
  12. ? ? data(){
  13. ? ? ? return{
  14. ? ? ? ? ? total:0
  15. ? ? ? }
  16. ? ? },
  17. ? ? methods:{
  18. ? ? ? incrementTotal1: function () { ? ? ? ? ? ? ? ? ? ? /*事件incrementTotal触发*/
  19. ? ? ? ? this.total += 1
  20. ? ? ? },
  21. ? ? ? incrementTotal2: function () { ? ? ? ? ? ? ? ? ? ?/*事件incrementTota2触发*/
  22. ? ? ? ? this.total += 2
  23. ? ? ? }
  24. ? ? },
  25. ? ? components:{ ? ? ? ? ? ? ? ? ? ? ? ?/*子组件的实例,要尽量放在最后,不然会出现一些不必要的问题*/
  26. ? ? ? myButton4
  27. ? ? }
  28. ? }
  29. </script>

2、子组件代码及说明

  1. <template>
  2. ? ? ? <button @click="incrementCounter">{{counter}}</button> <!--在子组件中创建一个按钮,创建点击事件-->
  3. </template>
  4.  
  5. <script>
  6. ? ?export default{
  7. ? ? ?data(){
  8. ? ? ? ?return{
  9. ? ? ? ? ?counter: 0
  10. ? ? ? ?}
  11. ? ? ?},
  12. ? ? ?methods: {
  13. ? ? ? ?incrementCounter: function (){
  14. ? ? ? ? ?this.counter += 1
  15. ? ? ? ? ?this.$emit('increment1') ? ? ? ?/*触发自定义事件increment1,也就是父组件中的incrementTotal1事件*/
  16. ? ? ? ? ?this.$emit('increment2') ? ? ? ?/*触发自定义事件increment2,也就是父组件中的incrementTotal2事件*/
  17. ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?/*这两个事件一次只会触发一个,为什么呢?很简单,因为每次只单击一个按钮*/
  18. ? ? ? ?}
  19. ? ? ?}
  20. ? ?}
  21. </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内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号