Directives

A directive that renders the items of an async iterable[1], appending new values after previous values, similar to the built-in support for iterables. This directive is usable only in child expressions.

导入

import { asyncAppend } from 'lit/directives/async-append.js';

签名

asyncAppend(value, _mapper?): DirectiveResult<AsyncAppendDirective>

参数

value
AsyncIterable<unknown>

An async iterable

_mapper?
(v: unknown, index?: number) => unknown

详情

Async iterables are objects with a [Symbol.asyncIterator] method, which returns an iterator who's next() method returns a Promise. When a new value is available, the Promise resolves and the value is appended to the Part controlled by the directive. If another value other than this directive has been set on the Part, the iterable will no longer be listened to and new values won't be written to the Part. [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of

An abstract Directive base class whose disconnected method will be called when the part containing the directive is cleared as a result of re-rendering, or when the user calls part.setConnected(false) on a part that was previously rendered containing the directive (as happens when e.g. a LitElement disconnects from the DOM).

导入

import { AsyncAppendDirective } from 'lit/directives/async-append.js';

详情

If part.setConnected(true) is subsequently called on a containing part, the directive's reconnected method will be called prior to its next update/render callbacks. When implementing disconnected, reconnected should also be implemented to be compatible with reconnection. Note that updates may occur while the directive is disconnected. As such, directives should generally check the this.isConnected flag during render/update to determine whether it is safe to subscribe to resources that may prevent garbage collection.

方法和属性

new AsyncAppendDirective(partInfo): AsyncAppendDirective

永久链接到 constructor
参数
partInfo
PartInfo

The connection state for this Directive.

commitValue(value, index): void

永久链接到 commitValue 查看源码
参数
value
unknown
index
number

User callbacks for implementing logic to release any resources/subscriptions that may have been retained by this directive. Since directives may also be re-connected, reconnected should also be implemented to restore the working state of the directive prior to the next render.

render(value, _mapper?): symbol

永久链接到 render 查看源码
参数
value
AsyncIterable<T>
_mapper?
Mapper<T>

Sets the value of the directive's Part outside the normal update/render lifecycle of a directive.

参数
value
unknown

The value to set

详情

This method should not be called synchronously from a directive's update or render.

update(part, params): undefined | noChange

永久链接到 update 查看源码
参数
part
ChildPart
params
[value, _mapper]

A directive that renders the items of an async iterable[1], replacing previous values with new values, so that only one value is ever rendered at a time. This directive may be used in any expression type.

导入

import { asyncReplace } from 'lit/directives/async-replace.js';

签名

asyncReplace(value, _mapper?): DirectiveResult<AsyncReplaceDirective>

参数

value
AsyncIterable<unknown>

An async iterable

_mapper?
Mapper<unknown>

详情

Async iterables are objects with a [Symbol.asyncIterator] method, which returns an iterator who's next() method returns a Promise. When a new value is available, the Promise resolves and the value is rendered to the Part controlled by the directive. If another value other than this directive has been set on the Part, the iterable will no longer be listened to and new values won't be written to the Part. [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of

An abstract Directive base class whose disconnected method will be called when the part containing the directive is cleared as a result of re-rendering, or when the user calls part.setConnected(false) on a part that was previously rendered containing the directive (as happens when e.g. a LitElement disconnects from the DOM).

导入

import { AsyncReplaceDirective } from 'lit/directives/async-replace.js';

详情

If part.setConnected(true) is subsequently called on a containing part, the directive's reconnected method will be called prior to its next update/render callbacks. When implementing disconnected, reconnected should also be implemented to be compatible with reconnection. Note that updates may occur while the directive is disconnected. As such, directives should generally check the this.isConnected flag during render/update to determine whether it is safe to subscribe to resources that may prevent garbage collection.

方法和属性

new AsyncReplaceDirective(_partInfo): AsyncReplaceDirective

永久链接到 constructor
参数
_partInfo
PartInfo

The connection state for this Directive.

commitValue(value, _index): void

永久链接到 commitValue 查看源码
参数
value
unknown
_index
number

User callbacks for implementing logic to release any resources/subscriptions that may have been retained by this directive. Since directives may also be re-connected, reconnected should also be implemented to restore the working state of the directive prior to the next render.

render(value, _mapper?): symbol

永久链接到 render 查看源码
参数
value
AsyncIterable<T>
_mapper?
Mapper<T>

Sets the value of the directive's Part outside the normal update/render lifecycle of a directive.

参数
value
unknown

The value to set

详情

This method should not be called synchronously from a directive's update or render.

update(_part, __namedParameters): undefined | noChange

永久链接到 update 查看源码
参数
_part
ChildPart
__namedParameters
[value, _mapper]

Enables fast switching between multiple templates by caching the DOM nodes and TemplateInstances produced by the templates.

导入

import { cache } from 'lit/directives/cache.js';

签名

cache(v): DirectiveResult<CacheDirective>

参数

v
unknown

详情

Example:

let checked = false;
html`
${cache(checked ? html`input is checked` : html`input is not checked`)}
`

Base class for creating custom directives. Users should extend this class, implement render and/or update, and then pass their subclass to directive.

导入

import { CacheDirective } from 'lit/directives/cache.js';

方法和属性

new CacheDirective(partInfo): CacheDirective

永久链接到 constructor
参数
partInfo
PartInfo

render(v): Array<unknown>

永久链接到 render 查看源码
参数
v
unknown

update(containerPart, __namedParameters): Array<unknown>

永久链接到 update 查看源码
参数
containerPart
ChildPart
__namedParameters
[v]

Chooses and evaluates a template function from a list based on matching the given value to a case.

导入

import { choose } from 'lit/directives/choose.js';

签名

choose(value, cases, defaultCase?): undefined | V

参数

value
T
cases
Array<[T, () => V]>
defaultCase?
() => V

详情

Cases are structured as [caseValue, func]. value is matched to caseValue by strict equality. The first match is selected. Case values can be of any type including primitives, objects, and symbols. This is similar to a switch statement, but as an expression and without fallthrough.

A directive that applies dynamic CSS classes.

导入

import { classMap } from 'lit/directives/class-map.js';

签名

classMap(classInfo): DirectiveResult<ClassMapDirective>

参数

classInfo
ClassInfo

详情

This must be used in the class attribute and must be the only part used in the attribute. It takes each property in the classInfo argument and adds the property name to the element's classList if the property value is truthy; if the property value is falsey, the property name is removed from the element's class. For example {foo: bar} applies the class foo if the value of bar is truthy.

Base class for creating custom directives. Users should extend this class, implement render and/or update, and then pass their subclass to directive.

导入

import { ClassMapDirective } from 'lit/directives/class-map.js';

方法和属性

new ClassMapDirective(partInfo): ClassMapDirective

永久链接到 constructor
参数
partInfo
PartInfo

render(classInfo): string

永久链接到 render 查看源码
参数
classInfo
ClassInfo

update(part, __namedParameters): string | noChange

永久链接到 update 查看源码
参数
part
AttributePart
__namedParameters
[classInfo]

A key-value set of class names to truthy values.

导入

import { ClassInfo } from 'lit/directives/class-map.js';

Prevents re-render of a template function until a single value or an array of values changes.

导入

import { guard } from 'lit/directives/guard.js';

签名

guard(_value, f): DirectiveResult<GuardDirective>

参数

_value
unknown
f
() => unknown

the template function

详情

Values are checked against previous values with strict equality (===), and so the check won't detect nested property changes inside objects or arrays. Arrays values have each item checked against the previous value at the same index with strict equality. Nested arrays are also checked only by strict equality. Example:

html`
<div>
${guard([user.id, company.id], () => html`...`)}
</div>
`

In this case, the template only rerenders if either user.id or company.id changes. guard() is useful with immutable data patterns, by preventing expensive work until data updates. Example:

html`
<div>
${guard([immutableItems], () => immutableItems.map(i => html`${i}`))}
</div>
`

In this case, items are mapped over only when the array reference changes.

Base class for creating custom directives. Users should extend this class, implement render and/or update, and then pass their subclass to directive.

导入

import { GuardDirective } from 'lit/directives/guard.js';

方法和属性

new GuardDirective(_partInfo): GuardDirective

永久链接到 constructor
参数
_partInfo
PartInfo

render(_value, f): unknown

永久链接到 render 查看源码
参数
_value
unknown
f
() => unknown

update(_part, __namedParameters): unknown

永久链接到 update 查看源码
参数
_part
Part
__namedParameters
[_value, f]

For AttributeParts, sets the attribute if the value is defined and removes the attribute if the value is undefined.

导入

import { ifDefined } from 'lit/directives/if-defined.js';

签名

ifDefined(value): nothing | NonNullable<T>

参数

value
T

详情

For other part types, this directive is a no-op.

Returns an iterable containing the values in items interleaved with the joiner value.

导入

import { join } from 'lit/directives/join.js';

签名

join(items, joiner): Iterable<I | J>

参数

items
undefined | Iterable<I>
joiner
(index: number) => J

Associates a renderable value with a unique key. When the key changes, the previous DOM is removed and disposed before rendering the next value, even if the value - such as a template - is the same.

导入

import { keyed } from 'lit/directives/keyed.js';

签名

keyed(k, v): DirectiveResult<Keyed>

参数

k
unknown
v
unknown

详情

This is useful for forcing re-renders of stateful components, or working with code that expects new data to generate new HTML elements, such as some animation techniques.

Base class for creating custom directives. Users should extend this class, implement render and/or update, and then pass their subclass to directive.

导入

import { Keyed } from 'lit/directives/keyed.js';

方法和属性

参数
_partInfo
PartInfo
参数
k
unknown
v
unknown

update(part, __namedParameters): unknown

永久链接到 update 查看源码
参数
part
ChildPart
__namedParameters
[k, v]

Checks binding values against live DOM values, instead of previously bound values, when determining whether to update the value.

导入

import { live } from 'lit/directives/live.js';

签名

live(value): DirectiveResult<LiveDirective>

参数

value
unknown

详情

This is useful for cases where the DOM value may change from outside of lit-html, such as with a binding to an <input> element's value property, a content editable elements text, or to a custom element that changes it's own properties or attributes. In these cases if the DOM value changes, but the value set through lit-html bindings hasn't, lit-html won't know to update the DOM value and will leave it alone. If this is not what you want--if you want to overwrite the DOM value with the bound value no matter what--use the live() directive:

html`<input .value=${live(x)}>`

live() performs a strict equality check against the live DOM value, and if the new value is equal to the live value, does nothing. This means that live() should not be used when the binding will cause a type conversion. If you use live() with an attribute binding, make sure that only strings are passed in, or the binding will update every render.

Base class for creating custom directives. Users should extend this class, implement render and/or update, and then pass their subclass to directive.

导入

import { LiveDirective } from 'lit/directives/live.js';

方法和属性

new LiveDirective(partInfo): LiveDirective

永久链接到 constructor
参数
partInfo
PartInfo
参数
value
unknown

update(part, __namedParameters): unknown

永久链接到 update 查看源码
参数
part
AttributePart
__namedParameters
[value]

Returns an iterable containing the result of calling f(value) on each value in items.

导入

import { map } from 'lit/directives/map.js';

签名

map(items, f): Generator<unknown, void, unknown>

参数

items
undefined | Iterable<T>
f
(value: T, index: number) => unknown

Returns an iterable of integers from start to end (exclusive) incrementing by step.

导入

import { range } from 'lit/directives/range.js';

签名

range(end): Iterable<number>

参数

end
number

详情

If start is omitted, the range starts at 0. step defaults to 1.

Creates a new Ref object, which is container for a reference to an element.

导入

import { createRef } from 'lit/directives/ref.js';

签名

createRef(): Ref<T>

Sets the value of a Ref object or calls a ref callback with the element it's bound to.

导入

import { ref } from 'lit/directives/ref.js';

签名

ref(_ref): DirectiveResult<RefDirective>

参数

_ref
RefOrCallback

详情

A Ref object acts as a container for a reference to an element. A ref callback is a function that takes an element as its only argument. The ref directive sets the value of the Ref object or calls the ref callback during rendering, if the referenced element changed. Note: If a ref callback is rendered to a different element position or is removed in a subsequent render, it will first be called with undefined, followed by another call with the new element it was rendered to (if any).

// Using Ref object
const inputRef = createRef();
render(html`<input ${ref(inputRef)}>`, container);
inputRef.value.focus();
// Using callback
const callback = (inputElement) => inputElement.focus();
render(html`<input ${ref(callback)}>`, container);

An object that holds a ref value.

导入

import { Ref } from 'lit/directives/ref.js';

方法和属性

The current Element value of the ref, or else undefined if the ref is no longer rendered.

An abstract Directive base class whose disconnected method will be called when the part containing the directive is cleared as a result of re-rendering, or when the user calls part.setConnected(false) on a part that was previously rendered containing the directive (as happens when e.g. a LitElement disconnects from the DOM).

导入

import { RefDirective } from 'lit/directives/ref.js';

详情

If part.setConnected(true) is subsequently called on a containing part, the directive's reconnected method will be called prior to its next update/render callbacks. When implementing disconnected, reconnected should also be implemented to be compatible with reconnection. Note that updates may occur while the directive is disconnected. As such, directives should generally check the this.isConnected flag during render/update to determine whether it is safe to subscribe to resources that may prevent garbage collection.

方法和属性

new RefDirective(_partInfo): RefDirective

永久链接到 constructor
参数
_partInfo
PartInfo

The connection state for this Directive.

User callbacks for implementing logic to release any resources/subscriptions that may have been retained by this directive. Since directives may also be re-connected, reconnected should also be implemented to restore the working state of the directive prior to the next render.

参数
_ref
RefOrCallback

Sets the value of the directive's Part outside the normal update/render lifecycle of a directive.

参数
value
unknown

The value to set

详情

This method should not be called synchronously from a directive's update or render.

update(part, __namedParameters): symbol

永久链接到 update 查看源码
参数
part
ElementPart
__namedParameters
[_ref]

导入

import { RefOrCallback } from 'lit/directives/ref.js';

类型

Ref | (el: MDN Element | undefined) => void

A directive that repeats a series of values (usually TemplateResults) generated from an iterable, and updates those items efficiently when the iterable changes based on user-provided keys associated with each item.

导入

import { repeat } from 'lit/directives/repeat.js';

签名

repeat(items, keyFnOrTemplate, template?): unknown

参数

items
Iterable<T>
keyFnOrTemplate
KeyFn<T> | ItemTemplate<T>
template?
ItemTemplate<T>

详情

Note that if a keyFn is provided, strict key-to-DOM mapping is maintained, meaning previous DOM for a given key is moved into the new position if needed, and DOM will never be reused with values for different keys (new DOM will always be created for new keys). This is generally the most efficient way to use repeat since it performs minimum unnecessary work for insertions and removals. The keyFn takes two parameters, the item and its index, and returns a unique key value.

html`
<ol>
${repeat(this.items, (item) => item.id, (item, index) => {
return html`<li>${index}: ${item.name}</li>`;
})}
</ol>
`

Important: If providing a keyFn, keys must be unique for all items in a given call to repeat. The behavior when two or more items have the same key is undefined. If no keyFn is provided, this directive will perform similar to mapping items to values, and DOM will be reused against potentially different items.

Base class for creating custom directives. Users should extend this class, implement render and/or update, and then pass their subclass to directive.

导入

import { RepeatDirective } from 'lit/directives/repeat.js';

方法和属性

new RepeatDirective(partInfo): RepeatDirective

永久链接到 constructor
参数
partInfo
PartInfo

render(items, template): Array<unknown>

永久链接到 render 查看源码
参数
items
Iterable<T>
template
ItemTemplate<T>

update(containerPart, __namedParameters): Array<unknown> | noChange

永久链接到 update 查看源码
参数
containerPart
ChildPart
__namedParameters
[Iterable<T>, KeyFn<T> | ItemTemplate<T>, ItemTemplate<T>]

导入

import { ItemTemplate } from 'lit/directives/repeat.js';

类型

(item: T, index: number) => unknown

导入

import { KeyFn } from 'lit/directives/repeat.js';

类型

(item: T, index: number) => unknown

导入

import { RepeatDirectiveFn } from 'lit/directives/repeat.js';

签名

RepeatDirectiveFn(items, keyFnOrTemplate, template?): unknown

参数

items
Iterable<T>
keyFnOrTemplate
KeyFn<T> | ItemTemplate<T>
template?
ItemTemplate<T>

A directive that applies CSS properties to an element.

导入

import { styleMap } from 'lit/directives/style-map.js';

签名

styleMap(styleInfo): DirectiveResult<StyleMapDirective>

参数

styleInfo
Readonly<StyleInfo>

详情

styleMap can only be used in the style attribute and must be the only expression in the attribute. It takes the property names in the styleInfo object and adds the properties to the inline style of the element. Property names with dashes (-) are assumed to be valid CSS property names and set on the element's style object using setProperty(). Names without dashes are assumed to be camelCased JavaScript property names and set on the element's style object using property assignment, allowing the style object to translate JavaScript-style names to CSS property names. For example styleMap({backgroundColor: 'red', 'border-top': '5px', '--size': '0'}) sets the background-color, border-top and --size properties.

Base class for creating custom directives. Users should extend this class, implement render and/or update, and then pass their subclass to directive.

导入

import { StyleMapDirective } from 'lit/directives/style-map.js';

方法和属性

new StyleMapDirective(partInfo): StyleMapDirective

永久链接到 constructor
参数
partInfo
PartInfo

render(styleInfo): string

永久链接到 render 查看源码
参数
styleInfo
Readonly<StyleInfo>

update(part, __namedParameters): string | noChange

永久链接到 update 查看源码
参数
part
AttributePart
__namedParameters
[styleInfo]

A key-value set of CSS properties and values.

导入

import { StyleInfo } from 'lit/directives/style-map.js';

详情

The key should be either a valid CSS property name string, like 'background-color', or a valid JavaScript camel case property name for CSSStyleDeclaration like backgroundColor.

Renders the content of a template element as HTML.

导入

import { templateContent } from 'lit/directives/template-content.js';

签名

templateContent(template): DirectiveResult<TemplateContentDirective>

参数

template
MDN HTMLTemplateElement

详情

Note, the template should be developer controlled and not user controlled. Rendering a user-controlled template with this directive could lead to cross-site-scripting vulnerabilities.

Base class for creating custom directives. Users should extend this class, implement render and/or update, and then pass their subclass to directive.

导入

import { TemplateContentDirective } from 'lit/directives/template-content.js';

方法和属性

new TemplateContentDirective(partInfo): TemplateContentDirective

永久链接到 constructor
参数
partInfo
PartInfo

update(_part, props): unknown

永久链接到 update 查看源码
参数
_part
Part
props
Array<unknown>

Renders the result as HTML, rather than text.

导入

import { unsafeHTML } from 'lit/directives/unsafe-html.js';

签名

unsafeHTML(value): DirectiveResult<UnsafeHTMLDirective>

参数

value
undefined | null | string | noChange | nothing

详情

The values undefined, null, and nothing, will all result in no content (empty string) being rendered. Note, this is unsafe to use with any user-provided input that hasn't been sanitized or escaped, as it may lead to cross-site-scripting vulnerabilities.

Base class for creating custom directives. Users should extend this class, implement render and/or update, and then pass their subclass to directive.

导入

import { UnsafeHTMLDirective } from 'lit/directives/unsafe-html.js';

方法和属性

new UnsafeHTMLDirective(partInfo): UnsafeHTMLDirective

永久链接到 constructor
参数
partInfo
PartInfo

render(value): undefined | null | noChange | nothing | TemplateResult<ResultType>

永久链接到 render 查看源码
参数
value
undefined | null | string | noChange | nothing

update(_part, props): unknown

永久链接到 update 查看源码
参数
_part
Part
props
Array<unknown>

Renders the result as SVG, rather than text.

导入

import { unsafeSVG } from 'lit/directives/unsafe-svg.js';

签名

unsafeSVG(value): DirectiveResult<UnsafeSVGDirective>

参数

value
undefined | null | string | noChange | nothing

详情

The values undefined, null, and nothing, will all result in no content (empty string) being rendered. Note, this is unsafe to use with any user-provided input that hasn't been sanitized or escaped, as it may lead to cross-site-scripting vulnerabilities.

Base class for creating custom directives. Users should extend this class, implement render and/or update, and then pass their subclass to directive.

导入

import { UnsafeSVGDirective } from 'lit/directives/unsafe-svg.js';

方法和属性

new UnsafeSVGDirective(partInfo): UnsafeSVGDirective

永久链接到 constructor
参数
partInfo
PartInfo

render(value): undefined | null | noChange | nothing | TemplateResult<ResultType>

永久链接到 render 查看源码
参数
value
undefined | null | string | noChange | nothing

update(_part, props): unknown

永久链接到 update 查看源码
参数
_part
Part
props
Array<unknown>

Renders one of a series of values, including Promises, to a Part.

导入

import { until } from 'lit/directives/until.js';

签名

until(values): DirectiveResult<UntilDirective>

参数

values
Array<unknown>

详情

Values are rendered in priority order, with the first argument having the highest priority and the last argument having the lowest priority. If a value is a Promise, low-priority values will be rendered until it resolves. The priority of values can be used to create placeholder content for async data. For example, a Promise with pending content can be the first, highest-priority, argument, and a non_promise loading indicator template can be used as the second, lower-priority, argument. The loading indicator will render immediately, and the primary content will render when the Promise resolves. Example:

const content = fetch('./content.txt').then(r => r.text());
html`${until(content, html`<span>Loading...</span>`)}`

An abstract Directive base class whose disconnected method will be called when the part containing the directive is cleared as a result of re-rendering, or when the user calls part.setConnected(false) on a part that was previously rendered containing the directive (as happens when e.g. a LitElement disconnects from the DOM).

导入

import { UntilDirective } from 'lit/directives/until.js';

详情

If part.setConnected(true) is subsequently called on a containing part, the directive's reconnected method will be called prior to its next update/render callbacks. When implementing disconnected, reconnected should also be implemented to be compatible with reconnection. Note that updates may occur while the directive is disconnected. As such, directives should generally check the this.isConnected flag during render/update to determine whether it is safe to subscribe to resources that may prevent garbage collection.

方法和属性

new UntilDirective(_partInfo): UntilDirective

永久链接到 constructor
参数
_partInfo
PartInfo

The connection state for this Directive.

User callbacks for implementing logic to release any resources/subscriptions that may have been retained by this directive. Since directives may also be re-connected, reconnected should also be implemented to restore the working state of the directive prior to the next render.

参数
args
Array<unknown>

Sets the value of the directive's Part outside the normal update/render lifecycle of a directive.

参数
value
unknown

The value to set

详情

This method should not be called synchronously from a directive's update or render.

update(_part, args): unknown

永久链接到 update 查看源码
参数
_part
Part
args
Array<unknown>

When condition is true, returns the result of calling trueCase(), else returns the result of calling falseCase() if falseCase is defined.

导入

import { when } from 'lit/directives/when.js';

签名

when(condition, trueCase, falseCase?): T

参数

condition
true
trueCase
() => T
falseCase?
() => F

详情

This is a convenience wrapper around a ternary expression that makes it a little nicer to write an inline conditional without an else.