Lit-Element 中组件加载后如何执行脚本

问题描述 投票:0回答:1

我尝试在组件加载后向输入的电话号码添加前缀,但出现错误。在普通的 Web 组件中,connectedCallback() 方法就足够了,但在这里它似乎不起作用。我该如何解决这个问题?

我收到的错误: 未捕获的类型错误:无法读取 null 的属性(读取“getAttribute”)

import { LitElement, html } from "https://cdn.jsdelivr.net/gh/lit/dist@3/core/lit-core.min.js";
import "https://unpkg.com/[email protected]/build/js/intlTelInput.min.js";
import { formattedArray } from "./countries.js";

export class Form extends LitElement {
  static properties = {
    name: {},
    modalContent: {},
  };

  constructor() {
    super();
    this.countries = formattedArray;
  }

  render() {
    return html`
      <form class="flex flex-col gap-3" @submit=${this.handleSubmit}>
        <input type="text" class="form-control" placeholder="First name" name="first_name" />
        <input type="text" class="form-control" placeholder="Last name" name="last_name" />
        <input type="text" class="form-control" placeholder="Address" name="address" />
        <input type="text" class="form-control" placeholder="Zip Code" name="zip" />
        <input type="text" class="form-control" placeholder="City" name="city" />
        <select class="form-control" name="country">
          ${this.countries.map(country => html`<option value="${country}">${country}</option>`)}
        </select>
        <input type="tel" class="form-control" placeholder="Phone" name="phone" id="phone" />
        <input type="email" class="form-control" placeholder="Email" name="email" />
        <button type="submit" class="btn btn-primary">
          Continue
        </button>
      </form>
    `;
  }

  connectedCallback() {
    super.connectedCallback();
    // Initialize intlTelInput
    const input = document.querySelector("#phone");
    window.intlTelInput(input, {
      initialCountry: "auto",
      separateDialCode: true,
      utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js", // Add the correct path to utils.js
    });
  }

  handleSubmit(event) {
    event.preventDefault();

    const formData = new FormData(event.target);
    const formObject = Object.fromEntries(formData.entries());

    // Do something with the form data, for example, log it
    console.log("Form data:", formObject);

    this.dispatchEvent(new Event('submitted', {bubbles: true, composed: true}));
  }

  createRenderRoot() {
    return this;
  }
}

customElements.define("custom-form", Form);

javascript web-component lit-element lit
1个回答
0
投票

lit 文档中所述 使用

firstUpdated
在创建元素模板后执行一次性工作。

firstUpdated() {
    // Initialize intlTelInput 
    const input = document.querySelector("#phone");
    window.intlTelInput(input, {
      initialCountry: "auto",
      separateDialCode: true,
      utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js", // Add the correct path to utils.js
    });
  } 

工作示例

© www.soinside.com 2019 - 2024. All rights reserved.