0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

litでdata属性を動的につける

Posted at

結論

<div data-hoge=${this.isHoge ? 'hoge' : 'piyo'}>data属性を持つ要素</div>

気をつけるポイント

  • data属性をつける判定に使う変数をreactiveな変数にしておく
    • propertyやstateなどにしておけばOK
  • ${}の中で三項演算子で書けばOK

コード例

import { LitElement, css, html } from 'lit'
import { customElement, state } from 'lit/decorators.js'


@customElement('data-attribute-example')
export class DataAttributeExample extends LitElement {

	@state()
	isHoge = true

	private changeHoge() {
		this.isHoge = !this.isHoge
	}

	render() {
		return html`
		<div class="hoge" data-hoge=${this.isHoge ? 'hoge' : 'piyo'}>data属性を持つ要素</div>
		<button @click=${this.changeHoge}>data属性の変更</button>
		`
	}

	static styles = css`
	.hoge {
		margin: 1em;
	}

	button {
		border-radius: 8px;
		border: 1px solid transparent;
		padding: 0.6em 1.2em;
		font-size: 1em;
		font-weight: 500;
		font-family: inherit;
		background-color: #f1f0f0;
		cursor: pointer;
		transition: border-color 0.25s;
	  }
	  button:hover {
		border-color: #646cff;
	  }
	  button:focus,
	  button:focus-visible {
		outline: 4px auto -webkit-focus-ring-color;
	  }
	  `
}

クリック前

image.png

クリック後

image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?