Logo

Developer learning path

JavaScript

Webкомпоненты в JavaScript

Webкомпоненты

60

#example

Пример 1: Создание и использование простого веб-компонента

                    
<!DOCTYPE html>
<html>
<head>
  <style>
    .custom-component {
      background-color: #f1f1f1;
      padding: 20px;
      border: 1px solid #ccc;
    }
  </style>
</head>
<body>

  <custom-component></custom-component>

  <script>
    class CustomComponent extends HTMLElement {
      constructor() {
        super();
        const shadow = this.attachShadow({ mode: 'open' });

        const container = document.createElement('div');
        container.className = 'custom-component';
        container.textContent = 'Привет, я кастомный веб-компонент!';

        shadow.appendChild(container);
      }
    }

    customElements.define('custom-component', CustomComponent);
  </script>

</body>
</html>
                  

Пример 2: Использование свойств и событий веб-компонента

                    
<!DOCTYPE html>
<html>
<head>
  <style>
    .custom-input {
      background-color: #f1f1f1;
      padding: 10px;
      border: 1px solid #ccc;
    }
  </style>
</head>
<body>

  <custom-input placeholder="Введите текст"></custom-input>
  <div id="output"></div>

  <script>
    class CustomInput extends HTMLElement {
      constructor() {
        super();
        const shadow = this.attachShadow({ mode: 'open' });

        const input = document.createElement('input');
        input.className = 'custom-input';

        input.addEventListener('input', (event) => {
          this.dispatchEvent(new CustomEvent('change', {
            detail: {
              value: event.target.value
            }
          }));
        });

        shadow.appendChild(input);
      }

      connectedCallback() {
        if (this.hasAttribute('placeholder')) {
          this.shadowRoot.querySelector('.custom-input').setAttribute('placeholder', this.getAttribute('placeholder'));
        }
      }
    }

    customElements.define('custom-input', CustomInput);

    const output = document.getElementById('output');

    const input = document.querySelector('custom-input');
    input.addEventListener('change', (event) => {
      output.textContent = `Введено: ${event.detail.value}`;
    });
  </script>

</body>
</html>
                  

В этих примерах мы создаем простые веб-компоненты: custom-component и custom-input. Первый компонент просто выводит текст, а второй компонент является пользовательским полем ввода с возможностью установки атрибута placeholder и возможностью отслеживать изменение значения в поле ввода с помощью события change.

February 6, 2024

Если вам не совсем понятен какой-то абзац текста из лекции, просто нажмите на него и сможете задать уточняющие вопросы по нему.

Если же непонятен весь вопрос, то нажмите на кнопки внизу, чтобы получить новый вариант объяснения, практические примеры или критически оценить сам вопрос.