b2nil / taro-ui-vue3

采用 Vue 3.0 重写的 Taro UI 组件库
https://b2nil.github.io/taro-ui-vue3/
MIT License
160 stars 51 forks source link

List item onClick/onSwitchChange 应该是action不是props #105

Closed pipinet closed 3 years ago

pipinet commented 3 years ago

如题

b2nil commented 3 years ago

List item onClick/onSwitchChange 应该是 action 不是 props

抱歉,您是指 onClick/onSwitchChange 等事件不应该放在 props 里面吗?Vue 的 action 具体是指什么?是指 emits 吗?

pipinet commented 3 years ago

是的。应该是emits出去。而不是通过props传入。

b2nil commented 3 years ago

Vue 3.0 文档确实是建议将自定义事件写在 emits 里面,rfc 里面也列出了为什么这么做的 5 条 Motivation

不过,由于 Vue 3.0 的渲染函数 api 采用了扁平式 VNode 结构,事件监听器 (event listeners) 都包含在了 $attrs 里面,以 on 开头的属性 (props) 会被处理为 v-on 绑定。

{
  class: ['foo', 'bar'],
  style: { color: 'red' },
  id: 'foo',
  innerHTML: '',
  onClick: foo,
  key: 'foo'
}

例如:

<Foo @click="foo" @custom-event="bar" />

无论自定义事件是写在 props 里面,还是 emits 里面,都会被会被编译为:

h(Foo , {
  onClick: foo,
  onCustomEvent: bar
})

在最终呈现效果和用法上,都是一致的。这一点跟 Vue 2 不同。

在 Vue 2 里,如果把自定义事件写在 props 里面,如: props: { onCustomEvent: Function }, 则不能使用 v-on 语法 @custom-event="bar" 来触发事件,只能使用 v-bind 语法,即 :onCustomEvent="bar" 来触发。

taro-ui-vue3 现在发布的 alpha 版本是直接采用渲染函数来写的,最大限度地利用了 taro-ui 原有的类型定义文件(便于使用 IDE 对 Typescript 的自动提示)。

现在有一个 feat/sfc 分支,正在使用 SFC 进行重构。其中事件声明部分就都采用 emits 来写了。有兴趣的话,欢迎来 PR。