对vue.js中this.$emit的深入理解

作者:有一个王小森 时间:2024-04-26 17:40:12 

对于vue.js中的this.emit的理解:this.emit(‘increment1',”这个位子是可以加参数的”);其实它的作用就是触发自定义函数。

看例子:


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<script src="vue.js"></script>
<body>
<div id="counter-event-example">
<p>{{ total }}</p>
<button-counter v-on:increment1="incrementTotal1"></button-counter>
<button-counter v-on:increment2="incrementTotal2"></button-counter>
</div>
</body>
<script>
Vue.component('button-counter', {
template: '<button v-on:click="increment">{{ counter }}</button>',
data: function () {
 return {
 counter: 0
 }
},
methods: {
 increment: function () {
 this.counter += 1;
 this.$emit('increment1',"这个位子是可以加参数的");//触发自定义increment1的函数。此处的increment1函数就是 incrementTotal1函数。
//  this.$emit('increment2'); //此时不会触发自定义increment2的函数。
 }
}
});
new Vue({
el: '#counter-event-example',
data: {
 total: 0
},
methods: {
 incrementTotal1: function (e) {
 this.total += 1;
 console.log(e);
 },
 incrementTotal2: function () {
 this.total += 1;
 }
}
})
</script>
</html>

对上面的例子进行进一步的解析:

1、首先看 自定组件button-counter ,给其绑定了方法 :increment;

2、点击button时会执行函数 increment,increment中有 this.$emit(‘increment1',”这个位子是可以加参数的”);

3、当increment执行时,就会触发自定函数increment1,也就是incrementTotal1函数;

4、而increment执行时没有触发自定义函数increment2,所以点击第二个按钮不执行incrementTotal2的函数。

来源:http://blog.csdn.net/wangxiaoxiaosen/article/details/75258013

标签:vue.js,this.$emit
0
投稿

猜你喜欢

  • python多线程+代理池爬取天天基金网、股票数据过程解析

    2023-07-22 12:26:28
  • 详解Spring Security怎么从数据库加载我们的用户

    2024-01-21 18:35:37
  • JS载入数据效果!loading

    2009-01-20 18:35:00
  • 有关Python的22个编程技巧

    2021-04-05 22:58:05
  • Python制作简单的网页爬虫

    2022-10-09 12:49:16
  • Python中如何导入类示例详解

    2023-05-09 08:35:58
  • CentOS 7下MySQL服务启动失败的快速解决方法

    2024-01-13 16:33:34
  • 对python3标准库httpclient的使用详解

    2021-09-07 06:48:02
  • 纯CSS Tooltips提示

    2008-10-18 16:01:00
  • SQL Server实现分布式数据库系统的终极目标

    2010-08-05 14:57:00
  • Python随机数模块详情

    2021-10-26 06:47:34
  • SQL server高并发生成唯一订单号的方法实现

    2024-01-21 21:24:55
  • Django-celery-beat动态添加周期性任务实现过程解析

    2021-07-29 13:09:49
  • centos7环境下二进制安装包安装 mysql5.6的方法详解

    2024-01-26 23:37:33
  • MySQL递归查询的3种实现方式实例

    2024-01-16 21:22:52
  • Python控制鼠标键盘代码实例

    2021-07-28 11:17:30
  • python 打印完整异常问题

    2022-11-04 16:04:11
  • Django 简单实现分页与搜索功能的示例代码

    2023-12-26 01:40:16
  • 3个适合新手练习的python小游戏

    2023-08-02 02:12:27
  • JavaScript如何获取一个元素的样式信息

    2023-08-28 12:16:17
  • asp之家 网络编程 m.aspxhome.com