-
Notifications
You must be signed in to change notification settings - Fork 545
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Attribute Fallthrough + Functional Component Updates #154
Changes from 3 commits
ab1a7e1
079454f
d6ebbcb
2043d82
158386a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,220 @@ | ||
- Start Date: 2019-11-05 | ||
- Target Major Version: 3.x | ||
- Reference Issues: N/A | ||
- Implementation PR: N/A | ||
|
||
# Summary | ||
|
||
- `v-on` listeners used on a component will fallthrough and be registered as native listeners on the child component root. `.native` modifier is no longer needed. | ||
|
||
- `inheritAttrs: false` now affects `class` and `style`. | ||
|
||
- `this.$attrs` now contains everything passed to the component minus those explicitly declared as props, including `class`, `style`, and `v-on` listeners. `this.$listeners` is removed. | ||
|
||
- Functional components attribute fallthrough behavior adjusted: | ||
- With explicit `props` declaration: full fallthrough like stateful components. | ||
- With no `props` declaration: only fallthrough for `class`, `style` and `v-on` listeners. | ||
|
||
# Motivation | ||
|
||
In Vue 2.x, components have an implicit attributes fallthrough behavior. Any attribute passed to a component that is not declared as a prop by the component, is considered an **extraneous attribute**. Fore example: | ||
|
||
``` html | ||
<MyComp id="foo"/> | ||
``` | ||
|
||
If `MyComp` didn't declare a prop named `id`, then the `id` is considered an extraneous attribute and will implicitly be applied to the root node of `MyComp`. | ||
|
||
This behavior is very convenient when tweaking layout styling between parent and child (by passing on `class` and `style`), or applying a11y attributes to child components. | ||
|
||
This behavior can be disabled with `inheritAttrs: false`, where the user expects to explicitly control where the attributes should be applied. These extraneous attributes are exposed in an instance property: `this.$attrs`. | ||
|
||
There are a number of inconsistencies and issues in the 2.x behavior: | ||
|
||
- `inheritAttrs: false` does not affect `class` and `style`. | ||
|
||
- Implicit fallthrough does not apply for event listeners, leading to the need for `.native` modifier if the user wish to add a native event listener to the child component root. | ||
|
||
- `class`, `style` and `v-on` listeners are not included in `$attrs`, making it cumbersome for a higher-order component (HOC) to properly pass everything down to a nested child component. | ||
|
||
- Functional components have no implicit attrs fallthrough behavior. | ||
|
||
In 3.x, we are also introducing Fragments (multiple root nodes in a component template), which require additional considerations on the behavior. | ||
|
||
# Detailed design | ||
|
||
## `v-on` Listener Fallthrough | ||
|
||
With the following usage: | ||
|
||
```html | ||
<MyButton @click="hello" /> | ||
``` | ||
|
||
- In v2, the `@click` will only register a component custom event listener. To attach a native listener to the root of `MyButton`, `@click.native` is needed. | ||
|
||
- In v3, the `@click` listener will fallthrough and register a native click listener on the root of `MyButton`. This means component authors no longer need to proxy native events to custom events in order to support `v-on` usage without the `.native` modifier. In fact, the `.native` modifier will be removed altogether. | ||
|
||
Note this may result in unnecessary registration of native event listeners when the user is only listening to component custom events, which we discuss below in [Unresolved Questions](#unresolved-questions). | ||
|
||
## Explicitly Controlling the Fallthrough | ||
|
||
### `inheritAttrs: false` | ||
|
||
With `inheritAttrs: false`, the implicit fallthrough is disabled. The component can either choose to intentionally ignore all extraneous attrs, or explicitly control where the attrs should be applied via `v-bind="$attrs"`: | ||
|
||
``` html | ||
<div class="wrapper"> | ||
<!-- apply attrs to an inner element instead of root --> | ||
<input v-bind="$attrs"> | ||
</div> | ||
``` | ||
|
||
`this.$attrs` (and `context.attrs` for `setup()` and functional components) now contains all attributes passed to the component (as long as it is not declared as props). This includes `class`, `style`, normal attributes and `v-on` listeners. This is based on the flat props structure proposed in [Render Function API Change](https://github.com/vuejs/rfcs/blob/master/active-rfcs/0008-render-function-api-change.md#flat-vnode-props-format). | ||
|
||
`v-on` listeners are included in `$attrs` as `onXXX` props. For example, `@click` will result in an `onClick` prop in `$attrs`. If the user wants to handle attributes and listeners separately, it can be done with simple helper functions that separate props that start with `on` from those that don't. | ||
|
||
### Multiple Root / Fragment Components | ||
|
||
In Vue 3, components can have multiple root elements (i.e. fragment root). In such cases, an automatic merge cannot be performed. The user will be responsible for spreading the attrs to the desired element: | ||
|
||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Sorry if this is an obvious question, with this proposal is there a way to manually indicate what native HTML element is represented by the component? For example, when building a component in React I can specify (in TypeScript) that my component extends I see here that Vue 3 will try to automatically do pass through, but won't if there's a fragmented root. There are also cases where you could have a wrapper div around a native There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This seems to be two separate questions. For TSX inference, it is possible but not as straightforward: const MyComponent = defineComponent({
props: {
foo: String
}
})
const MyComponentWithButtonProps = MyComponent as {
new(): InstanceType<typeof MyComponent> & { $props: JSX.IntrinsicElements['a'] }
}
// voila
<MyComponentWithButtonProps href="foo" /> A helper type can be used to make this cleaner: type ExtendProps<Comp extends { new(): any }, elements extends string> = {
new(): InstanceType<Comp> & { $props: JSX.IntrinsicElements[elements] }
}
const MyCompWithButtonProps = MyComponent as ExtendProps<typeof MyComponent, 'a'> // you can even use a union type to extend multiple elements For fragment root / wrapper elements, you can always manually control where the There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yeah I got that you could manually place the attrs anywhere, I just wanted to make sure you could indicate in the types which element you are applying them to. Thanks! |
||
``` html | ||
<template> | ||
<span>hello</span> | ||
<div v-bind="$attrs">main element</div> | ||
</template> | ||
``` | ||
|
||
If `$attrs` is non-empty, and the user did not perform an explicit spread (checked by access to `this.$attrs` during render), a runtime warning will be emitted. The component should either bind `$attrs` to an element, or explicitly suppress the warning with `inheritAttrs: false`. | ||
|
||
### In Render Functions | ||
|
||
In manual render functions, it may seem convenient to just use a spread: | ||
|
||
``` js | ||
export default { | ||
props: { /* ... */ }, | ||
inheritAttrs: false, | ||
render() { | ||
return h('div', { class: 'foo', ...this.$attrs }) | ||
} | ||
} | ||
``` | ||
|
||
However, this will cause attrs to overwrite whatever existing props of the same name. For example, there the local `class` may be overwritten when we probably want to merge the classes instead. Vue provides a `mergeProps` helper that handles the merging of `class`, `style` and `onXXX` listeners: | ||
|
||
``` js | ||
import { mergeProps } from 'vue' | ||
|
||
export default { | ||
props: { /* ... */ }, | ||
inheritAttrs: false, | ||
render() { | ||
return h('div', mergeProps({ class: 'foo' }, this.$attrs)) | ||
} | ||
} | ||
``` | ||
|
||
This is also what `v-bind` uses internally. | ||
|
||
If returning the render function from `setup`, the attrs object is exposed on the setup context: | ||
|
||
``` js | ||
import { mergeProps } from 'vue' | ||
|
||
export default { | ||
props: { /* ... */ }, | ||
inheritAttrs: false, | ||
setup(props, { attrs }) { | ||
return () => { | ||
return h('div', mergeProps({ class: 'foo' }, attrs)) | ||
} | ||
} | ||
} | ||
``` | ||
|
||
Note the `attrs` object is updated before every render, so it's ok to destructure it. | ||
|
||
## Functional Components | ||
|
||
In 2.x, functional components do not support automatic attribute fallthrough and require manual props merging. | ||
|
||
In v3, functional components use a different syntax: they are now declared as plain functions (as specified in [Render Function API Change](https://github.com/vuejs/rfcs/blob/master/active-rfcs/0008-render-function-api-change.md#functional-component-signature)). | ||
|
||
### With Explicit Props Declaration | ||
|
||
A functional component with `props` declaration will have the same automatic fallthrough behavior as stateful components. It can also explicitly control the attrs with `inheritAttrs: false`: | ||
|
||
``` js | ||
const Func = (props, { attrs }) => { | ||
return h('div', mergeProps({ class: 'foo' }, attrs), 'hello') | ||
} | ||
|
||
Func.props = { /*...*/ } | ||
Func.inheritAttrs = false | ||
``` | ||
|
||
### With Optional Props Declaration | ||
|
||
v3 functional components also support [Optional Props Declaration](#TODO). When a functional component has no `props` option defined, it receives all attributes passed by the parent as its `props`: | ||
|
||
``` js | ||
const Foo = props => h('div', { class: 'foo' }, props.msg) | ||
``` | ||
|
||
When a functional component is leveraging optional props declaration, there is only implicit fallthrough for `class`, `style`, and `v-on` listeners. | ||
|
||
The reason for `class`, `style` and `v-on` listeners to be whitelisted is because: | ||
|
||
- They cover the most common use cases for attribute fallthrough. | ||
- They have close to no risk of clashing with prop names. | ||
- They require special merge logic instead of simple overwrites, so handling them implicitly yields more convenience value. | ||
|
||
If a functional component with optional props declaration needs to support full attribute fallthrough, it needs to declare `inheritAttrs: false`, pick the desired attrs from `props`, and merge it to the root element: | ||
|
||
``` js | ||
// destructure props, and use rest spread to grab unused ones as attrs. | ||
const Func = ({ msg, ...attrs }) => { | ||
return h('div', mergeProps({ class: 'foo' }, attrs), msg) | ||
} | ||
Func.inheritAttrs = false | ||
``` | ||
|
||
## API Deprecations | ||
|
||
- `.native` modifier for v-on will be removed. | ||
- `this.$listeners` will be removed. | ||
|
||
# Adoption strategy | ||
|
||
- Deprecations can be supported in the compat build: | ||
|
||
- `.native` modifier will be a no-op and emit a warning during template compilation. | ||
- `this.$listeners` can be supported with a runtime warning. | ||
|
||
- There could technically be cases where the user relies on the 2.x behavior where `inheritAttrs: false` does not affect `class` and `style`, but it should be very rare. We will have a dedicated item in the migration guide / helper to remind the developer to check for such cases. | ||
|
||
- Since functional components uses a new syntax, they will likely require manual upgrades. We should have a dedicated section for functional components in the migration guide. | ||
|
||
# Unresolved questions | ||
|
||
## Removing Unwanted Listeners | ||
|
||
With flat VNode data and the removal of `.native` modifier, all listeners are passed down to the child component as `onXXX` functions: | ||
|
||
``` html | ||
<foo @click="foo" @custom="bar" /> | ||
``` | ||
|
||
compiles to: | ||
|
||
``` js | ||
h(foo, { | ||
onClick: foo, | ||
onCustom: bar | ||
}) | ||
``` | ||
|
||
When spreading `$attrs` with `v-bind`, all parent listeners are applied to the target element as native DOM listeners. The problem is that these same listeners can also be triggered by custom events - in the above example, both a native click event and a custom one emitted by `this.$emit('click')` in the child will trigger the parent's `foo` handler. This may lead to unwanted behavior. | ||
|
||
Props do not suffer from this problem because declared props are removed from `$attrs`. Therefore we should have a similar way to "declare" emitted events from a component. Event listeners for explicitly declared events will be removed from `$attrs` and can only be triggered by custom events emitted by the component via `this.$emit`. There is currently [an open RFC for it](https://github.com/vuejs/rfcs/pull/16) by @niko278. It is complementary to this RFC but does not affect the design of this RFC, so we can leave it for consideration at a later stage, even after Vue 3 release. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. To support just
Compare that with a v2 behaviour where nothing is required to get this behaviour out of the box and for arbitrary attributes only Even if #16 does become implemented there're too many workarounds required for just custom events to be able to safely work. I can hardly imagine Consider this example: <input @input="$emit('input', $event)" v-bind="$attrs"> If you do this in v3 then you should get 2 In each of those scenarios you should always filter There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Honestly I don't understand your concerns, so I'll just answer with what I think might address it:
So the only extra thing you need is the There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Having to add a The naming could probably be reconsidered though. I suggest leaving the modifier behaviour but calling it The problem with this approach is that it simplifies things if you need your listeners on the root element and complicates things if you need them somewhere else. It also complicates things if you have root event listeners emitting anything but the So some components will benefit from that and others will require more work than usual. Vue 2 does not have that problem. Maybe a balance could be achieved here? Consider a component that has to have implicit attributes fallthrough, but at the same time emit a custom event: <input @input="$emit('input', $event.target.value)" v-bind="filteredAttrs">
<script>
export default {
inheritAttrs: false,
computed: {
filteredAttrs() {...}
}
}
</script> The component above should benefit from attributes fallthrough in theory but it has to disable that behaviour in order to have a custom event. Since #16 is not part of this RFC at the current state this is how I imagine it's supposed to work for this case when this RFC is accepted. If the new behaviour requires There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Getting rid of There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. So, the primary concern is for components that emit custom events with the same names as native events? How often does that really happen? For most components that are wrappers of native equivalents (e.g. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. In my codebase this happens a lot. This change would stop me from migrating to v3. Also there is not a single case of There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @CyberAP assuming There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. That does resolve my problem provided that this migration step is not manual. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Technically a codemod can scan all instances of |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Given
MyButton
is authored that way would it produce 2 click events with implicit event listeners fallthrough?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yep, the whole point is you don't proxy events anymore.