对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
投稿

猜你喜欢

  • MySQL explain获取查询指令信息原理及实例

    2024-01-22 15:25:54
  • Python的文本常量与字符串模板之string库

    2022-04-11 05:13:25
  • pycharm安装包失败的解决方法

    2022-03-29 04:24:04
  • 解析python中的jsonpath 提取器

    2021-11-18 23:06:04
  • 从Pytorch模型pth文件中读取参数成numpy矩阵的操作

    2021-12-27 11:05:53
  • PHP图片上传类带图片显示

    2024-05-22 10:06:19
  • JavaScript运动框架 多值运动(四)

    2023-09-08 01:44:51
  • 详解SQLServer和Oracle的分页查询

    2024-01-21 10:11:39
  • Python 计算任意两向量之间的夹角方法

    2022-11-10 07:01:47
  • mysql如何统计同一字段不同值的个数

    2024-01-26 17:46:33
  • python操作toml文件的示例代码

    2023-06-12 03:58:33
  • MySQL 管理

    2024-01-13 14:42:43
  • 再谈float菜单局中

    2009-12-21 19:57:00
  • python geemap的安装步骤及环境配置

    2023-05-13 18:07:35
  • Javascript 类型转换方法

    2024-04-10 10:51:21
  • 利用Python操作excel表格的完美指南

    2022-05-21 07:59:09
  • 在Golang中使用http.FileServer返回静态文件的操作

    2024-02-20 07:51:50
  • Python 队列Queue和PriorityQueue解析

    2023-07-15 20:31:11
  • Mysql常用运算符与函数汇总

    2024-01-17 21:36:02
  • ASP.NET页面间的传值的几种方法

    2024-05-11 09:26:52
  • asp之家 网络编程 m.aspxhome.com