Vue Slot Props
在Vue中,slot是很实用的api,父组件可以很容易通过插槽向子组件插入内容,插槽还分为单个插槽,多个插槽和作用域插槽。 在React中,能不能实现和插槽一样的功能呢?当然有了,我们分别来看.
You’re browsing the documentation for v2.x and earlier. For v3.x, click here.
- In this course, you'll learn how to use slots and scoped slots to create flexible and reusable Vue.js components. Slots allow us to pass components and HTML to components, giving us greater control of the appearance than what we get with props.
- Slot props allow us to turn slots into reusable templates that can render different content based on input props. This is most useful when you are designing a reusable component that encapsulates data logic while allowing the consuming parent component to customize part of its layout.
- Practical Use Case of Vue Slots To pass down Html elements from one component to another. With props, Vue allows us to pass strings, objects, arrays, and functions from a parent component to its child component.
- When crafting components with Vue.js you can go multiple ways. You can go with the props based approach or you can choose the slot based solution. If you’re using props, things can quickly get out.
This page assumes you’ve already read the Components Basics. Read that first if you are new to components.
Prop Casing (camelCase vs kebab-case)
HTML attribute names are case-insensitive, so browsers will interpret any uppercase characters as lowercase. That means when you’re using in-DOM templates, camelCased prop names need to use their kebab-cased (hyphen-delimited) equivalents:
Again, if you’re using string templates, this limitation does not apply.
Prop Types
So far, we’ve only seen props listed as an array of strings:
Usually though, you’ll want every prop to be a specific type of value. In these cases, you can list props as an object, where the properties’ names and values contain the prop names and types, respectively:
This not only documents your component, but will also warn users in the browser’s JavaScript console if they pass the wrong type. You’ll learn much more about type checks and other prop validations further down this page.
Passing Static or Dynamic Props
So far, you’ve seen props passed a static value, like in:
You’ve also seen props assigned dynamically with v-bind
, such as in:
In the two examples above, we happen to pass string values, but any type of value can actually be passed to a prop.
Passing a Number
Vue Slot Props Games
Passing a Boolean
Passing an Array
Passing an Object
Passing the Properties of an Object
If you want to pass all the properties of an object as props, you can use v-bind
without an argument (v-bind
instead of v-bind:prop-name
). For example, given a post
object:
The following template:
Will be equivalent to:
One-Way Data Flow
All props form a one-way-down binding between the child property and the parent one: when the parent property updates, it will flow down to the child, but not the other way around. This prevents child components from accidentally mutating the parent’s state, which can make your app’s data flow harder to understand.
In addition, every time the parent component is updated, all props in the child component will be refreshed with the latest value. This means you should not attempt to mutate a prop inside a child component. If you do, Vue will warn you in the console.
There are usually two cases where it’s tempting to mutate a prop:
The prop is used to pass in an initial value; the child component wants to use it as a local data property afterwards. In this case, it’s best to define a local data property that uses the prop as its initial value:
The prop is passed in as a raw value that needs to be transformed. In this case, it’s best to define a computed property using the prop’s value:
Note that objects and arrays in JavaScript are passed by reference, so if the prop is an array or object, mutating the object or array itself inside the child component will affect parent state.
Prop Validation
Components can specify requirements for their props, such as the types you’ve already seen. If a requirement isn’t met, Vue will warn you in the browser’s JavaScript console. This is especially useful when developing a component that’s intended to be used by others.
To specify prop validations, you can provide an object with validation requirements to the value of props
, instead of an array of strings. For example:
When prop validation fails, Vue will produce a console warning (if using the development build).
Note that props are validated before a component instance is created, so instance properties (e.g. data
, computed
, etc) will not be available inside default
or validator
functions.
Type Checks
The type
can be one of the following native constructors:
- String
- Number
- Boolean
- Array
- Object
- Date
- Function
- Symbol
In addition, type
can also be a custom constructor function and the assertion will be made with an instanceof
check. For example, given the following constructor function exists:
You could use:
to validate that the value of the author
prop was created with new Person
.
Non-Prop Attributes
A non-prop attribute is an attribute that is passed to a component, but does not have a corresponding prop defined.
While explicitly defined props are preferred for passing information to a child component, authors of component libraries can’t always foresee the contexts in which their components might be used. That’s why components can accept arbitrary attributes, which are added to the component’s root element.
For example, imagine we’re using a 3rd-party bootstrap-date-input
component with a Bootstrap plugin that requires a data-date-picker
attribute on the input
. We can add this attribute to our component instance:
And the data-date-picker='activated'
attribute will automatically be added to the root element of bootstrap-date-input
.
Replacing/Merging with Existing Attributes
Imagine this is the template for bootstrap-date-input
:
To specify a theme for our date picker plugin, we might need to add a specific class, like this:
In this case, two different values for class
are defined:
form-control
, which is set by the component in its templatedate-picker-theme-dark
, which is passed to the component by its parent
For most attributes, the value provided to the component will replace the value set by the component. So for example, passing type='text'
will replace type='date'
and probably break it! Fortunately, the class
and style
attributes are a little smarter, so both values are merged, making the final value: form-control date-picker-theme-dark
.
Disabling Attribute Inheritance
If you do not want the root element of a component to inherit attributes, you can set inheritAttrs: false
in the component’s options. For example:
This can be especially useful in combination with the $attrs
instance property, which contains the attribute names and values passed to a component, such as:
With inheritAttrs: false
and $attrs
, you can manually decide which element you want to forward attributes to, which is often desirable for base components:
Note that inheritAttrs: false
option does not affect style
and class
bindings.
This pattern allows you to use base components more like raw HTML elements, without having to care about which element is actually at its root:
You’re browsing the documentation for v2.x and earlier. For v3.x, click here.
This page assumes you’ve already read the Components Basics. Read that first if you are new to components.
In 2.6.0, we introduced a new unified syntax (the v-slot
directive) for named and scoped slots. It replaces the slot
and slot-scope
attributes, which are now deprecated, but have not been removed and are still documented here. The rationale for introducing the new syntax is described in this RFC.
Slot Content
Vue implements a content distribution API inspired by the Web Components spec draft, using the <slot>
element to serve as distribution outlets for content.
This allows you to compose components like this:
Then in the template for <navigation-link>
, you might have:
When the component renders, <slot></slot>
will be replaced by “Your Profile”. Slots can contain any template code, including HTML:
Or even other components:
If <navigation-link>
‘s template did not contain a <slot>
element, any content provided between its opening and closing tag would be discarded.
Compilation Scope
When you want to use data inside a slot, such as in:
That slot has access to the same instance properties (i.e. the same “scope”) as the rest of the template. The slot does not have access to <navigation-link>
‘s scope. For example, trying to access url
would not work:
As a rule, remember that:
Everything in the parent template is compiled in parent scope; everything in the child template is compiled in the child scope.
Fallback Content
There are cases when it’s useful to specify fallback (i.e. default) content for a slot, to be rendered only when no content is provided. For example, in a <submit-button>
component:
We might want the text “Submit” to be rendered inside the <button>
most of the time. To make “Submit” the fallback content, we can place it in between the <slot>
tags:
Now when we use <submit-button>
in a parent component, providing no content for the slot:
will render the fallback content, “Submit”:
But if we provide content:
Then the provided content will be rendered instead:
Named Slots
Updated in 2.6.0+. See here for the deprecated syntax using the slot
attribute.
There are times when it’s useful to have multiple slots. For example, in a <base-layout>
component with the following template:
For these cases, the <slot>
element has a special attribute, name
, which can be used to define additional slots:
A <slot>
outlet without name
implicitly has the name “default”.
To provide content to named slots, we can use the v-slot
directive on a <template>
, providing the name of the slot as v-slot
‘s argument:
Now everything inside the <template>
elements will be passed to the corresponding slots. Any content not wrapped in a <template>
using v-slot
is assumed to be for the default slot.
However, you can still wrap default slot content in a <template>
if you wish to be explicit:
Either way, the rendered HTML will be:
Note that v-slot
can only be added to a <template>
(with one exception), unlike the deprecated slot
attribute.
Scoped Slots
Updated in 2.6.0+. See here for the deprecated syntax using the slot-scope
attribute.
Sometimes, it’s useful for slot content to have access to data only available in the child component. For example, imagine a <current-user>
component with the following template:
We might want to replace this fallback content to display the user’s first name, instead of last, like this:
That won’t work, however, because only the <current-user>
component has access to the user
and the content we’re providing is rendered in the parent.
To make user
available to the slot content in the parent, we can bind user
as an attribute to the <slot>
element:
Attributes bound to a <slot>
element are called slot props. Now, in the parent scope, we can use v-slot
with a value to define a name for the slot props we’ve been provided:
In this example, we’ve chosen to name the object containing all our slot props slotProps
, but you can use any name you like.
Abbreviated Syntax for Lone Default Slots
In cases like above, when only the default slot is provided content, the component’s tags can be used as the slot’s template. This allows us to use v-slot
directly on the component:
This can be shortened even further. Just as non-specified content is assumed to be for the default slot, v-slot
without an argument is assumed to refer to the default slot:
Note that the abbreviated syntax for default slot cannot be mixed with named slots, as it would lead to scope ambiguity:
Whenever there are multiple slots, use the full <template>
based syntax for all slots:
Destructuring Slot Props
Internally, scoped slots work by wrapping your slot content in a function passed a single argument:
That means the value of v-slot
can actually accept any valid JavaScript expression that can appear in the argument position of a function definition. So in supported environments (single-file components or modern browsers), you can also use ES2015 destructuring to pull out specific slot props, like so:
This can make the template much cleaner, especially when the slot provides many props. It also opens other possibilities, such as renaming props, e.g. user
to person
:
You can even define fallbacks, to be used in case a slot prop is undefined:
Dynamic Slot Names
New in 2.6.0+
Dynamic directive arguments also work on v-slot
, allowing the definition of dynamic slot names:
Named Slots Shorthand
New in 2.6.0+
Similar to v-on
and v-bind
, v-slot
also has a shorthand, replacing everything before the argument (v-slot:
) with the special symbol #
. For example, v-slot:header
can be rewritten as #header
:
However, just as with other directives, the shorthand is only available when an argument is provided. That means the following syntax is invalid:
Instead, you must always specify the name of the slot if you wish to use the shorthand:
Other Examples
Slot props allow us to turn slots into reusable templates that can render different content based on input props. This is most useful when you are designing a reusable component that encapsulates data logic while allowing the consuming parent component to customize part of its layout.
For example, we are implementing a <todo-list>
component that contains the layout and filtering logic for a list:
Instead of hard-coding the content for each todo, we can let the parent component take control by making every todo a slot, then binding todo
as a slot prop:
Now when we use the <todo-list>
component, we can optionally define an alternative <template>
for todo items, but with access to data from the child:
However, even this barely scratches the surface of what scoped slots are capable of. For real-life, powerful examples of scoped slot usage, we recommend browsing libraries such as Vue Virtual Scroller, Vue Promised, and Portal Vue.
Vue Slot Pass Props
Deprecated Syntax
The v-slot
directive was introduced in Vue 2.6.0, offering an improved, alternative API to the still-supported slot
and slot-scope
attributes. The full rationale for introducing v-slot
is described in this RFC. The slot
and slot-scope
attributes will continue to be supported in all future 2.x releases, but are officially deprecated and will eventually be removed in Vue 3.
Named Slots with the slot
Attribute
Deprecated in 2.6.0+. See here for the new, recommended syntax.
To pass content to named slots from the parent, use the special slot
attribute on <template>
(using the <base-layout>
component described here as example):
Or, the slot
attribute can also be used directly on a normal element:
There can still be one unnamed slot, which is the default slot that serves as a catch-all for any unmatched content. In both examples above, the rendered HTML would be:
Scoped Slots with the slot-scope
Attribute
Deprecated in 2.6.0+. See here for the new, recommended syntax.
To receive props passed to a slot, the parent component can use <template>
with the slot-scope
attribute (using the <slot-example>
described here as example):
Here, slot-scope
declares the received props object as the slotProps
variable, and makes it available inside the <template>
scope. You can name slotProps
anything you like similar to naming function arguments in JavaScript.
Vue Slot Examples
Here slot='default'
can be omitted as it is implied:
V Slot Vue
The slot-scope
attribute can also be used directly on a non-<template>
element (including components):
The value of slot-scope
can accept any valid JavaScript expression that can appear in the argument position of a function definition. This means in supported environments (single-file components or modern browsers) you can also use ES2015 destructuring in the expression, like so:
Using the <todo-list>
described here as an example, here’s the equivalent usage using slot-scope
: