惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX
酷 壳 – CoolShell
酷 壳 – CoolShell
美团技术团队
有赞技术团队
有赞技术团队
Hugging Face - Blog
Hugging Face - Blog
罗磊的独立博客
S
SegmentFault 最新的问题
D
Docker
博客园 - 司徒正美
雷峰网
雷峰网
V
Visual Studio Blog
云风的 BLOG
云风的 BLOG
G
Google Developers Blog
The GitHub Blog
The GitHub Blog
A
About on SuperTechFans
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - Franky
月光博客
月光博客
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
The Blog of Author Tim Ferriss
Google DeepMind News
Google DeepMind News
MyScale Blog
MyScale Blog
MongoDB | Blog
MongoDB | Blog

愆伏

vue feedback 指令开发 通过webpack对css压缩后所引起的重名问题 NPM 撤回已发布的版本 昆虫有趋光性吗 数组转成字符串(css 属性) 关于grid布局的一些思考 阿里云和腾讯云网站字体族对比 Vue 事件参数传递 Vue Data里面下划线命名无效并报错 使用sublime中的正则处理数据格式 通过nodejs创建目录与文件 macOS 下npm run dev 无法局域网访问 mac 下使用ssh访问非22端口的gitlab 世界是平的,在科学上网之后 使用sublime text3和Markdown来写博客 如果非要给一个标题,那就是2014年非工作总结 不专业呢,就别捣乱 对知乎大号怒撤事件的一点看法 拒绝SB思维 嘀嘀与快的的商业博弈 关于收藏夹功能的思考 你居然都不用微信 一个英语培训机构的外呼电话 智商是硬伤就无解了 扁鹊三兄弟 竖子不足与谋 美丽说、蘑菇街今天一定开了好几个小时的会 个人独立博客会死掉吗? iPad作画 google reader即将关闭,谁来候补?
Vue组件抛事件和Function prop的差别
tortorse · 2018-01-15 · via 愆伏

1. emit event

child component

1
2
3
4
5
6
7
8
9
10
11
12
13
<template>
<button @click="foo">Button</button>
</template>
<script>
export default {
name: 'my-button',
methods:{
foo () {
this.$emit('onClick')
}
}
}
</script>

parent component

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<template>
<my-button @onClick="handleClick"></my-button>
</template>
<script>
import myButton from '@/components/myButton'
export default {
components: { myButton }
methods: {
handleClick () {
console.log('boo')
}
}
}
</script>

2. props function

child component

1
2
3
4
5
6
7
8
9
10
11
12
13
<template>
<button @click="onClick">Button</button>
</template>
<script>
export default {
name: 'my-button',
props: {
onClick: {
type: Function
}
}
}
</script>

parent component

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<template>
<my-button :onClick="handleClick"></my-button>
</template>
<script>
import myButton from '@/components/myButton'
export default {
components: { myButton }
methods: {
handleClick () {
console.log('boo')
}
}
}
</script>

3. 实验结果和理解

父组件不知道事件什么时候会发生,因为事件的监听和处理都在子组件

子组件不知道父组件在事件发生后干什么,因为干什么是执行的父组件里的method

子组件要求父组件提供一个Callback函数,当事件发生时子组件去回调父组件提供的Callback函数

两种方式的运行结果是一样的,写法上和理解上有差别。

  1. 在emit的情况下

    父组件能够监听到事件的发生,并且决定在事件发生时做什么

  2. 在props的情况下

    父组件不知道事件发生与否,只能指令子组件在发生时做什么处理

4. 可能的问题

  1. 是否存在父组件要对子组件产生的事件进行搜集并处理? 第二种方式可能就歇菜
  2. 第二种方式对传入的Function内部是无法校验的,不过第一种也只是回避,本来就不校验