Litelement querySelector is Null - PullRequest
       43

Litelement querySelector is Null

0 голосов
/ 16 октября 2018

У меня есть родительский файл index.js, который отображает дочерний тег counter.js.Всякий раз, когда свойство child изменяется, происходит событие, и родитель слушает его.Чтобы это работало, я должен отобразить оба тега в index.html, иначе index.js не может прослушивать как querySelector, извлекающий значение Null.Я хочу избежать использования тега x-counter в index.html.Пожалуйста, посмотрите на файлы по ссылке ниже: https://stackblitz.com/edit/js-fxhcp8

Вот мои 3 файла:

//1) index.js (Parent)
class XApp extends PolymerElement {
  constructor() {
    super();
    this.a = 15;
  }

  ready(){ 
    console.log("Done");
    super.ready();
    document.querySelector('x-counter').addEventListener('valueChange',function(e){
      console.log(e);
    });
}
  static get template() {
    return html`
     <x-counter></x-counter>
    `;
  }
}

customElements.define('x-app', XApp);

//2) counter.js (Child)
import { LitElement, html, property } from '@polymer/lit-element';

class XCounter extends LitElement {
  static get properties() {
    return {
      value: { type: Number }
    }
  }

  constructor() {
    super();
    this.value = 0;
  }

  render() {
    return html`
      <style>
        button, p {
          display: inline-block;
        }
      </style>
      <button @click="${() => this.decrement()}" aria-label="decrement">-</button>
      <p>${this.value}</p>
      <button @click="${() => this.increment()}" aria-label="increment">+</button>
    `;
  }

  decrement() {
    this.value--;
    this._valueChanged();
  }

  increment() {
    this.value++;
    this._valueChanged();
  }

  _valueChanged() {
    this.dispatchEvent(new CustomEvent('valueChange', { detail: this.value }));
  }
}

customElements.define('x-counter', XCounter);

//index.html
<!doctype html>
<html>
  <body>
<!-- Error without the below tag-->
      **<x-counter></x-counter>**
    <br />
    <x-app></x-app>
  </body>
</html>

1 Ответ

0 голосов
/ 20 октября 2018

Вот рабочий пример: я редактирую ваш код.Ваш код почти готов, я сделал небольшие изменения:

DEMO

import { PolymerElement, html } from '@polymer/polymer/polymer-element.js';

import './x-counter.js';

class IndexApp extends PolymerElement {
   constructor() {
    super();
    this.a = 15;
    this.addEventListener('value-changed', this._valueChanged)
  }

  static get template() {
    return html`
     <div>Parent element value : [[a]]</div>
      <x-counter 
         val="{{a}}" > 
      </x-counter>
    `;
  }
  _valueChanged(x){
      this.set('a', x.detail.val);
  }
}
customElements.define('index-app', IndexApp);

И х-счетчик:

import {LitElement, html, property} from '@polymer/lit-element';

class XCounter extends LitElement {
  static get properties() {
    return {
      val: { 
        type: Number 
        }
    }
  }

  render() {
    return html`
      <style>
        button, p {
          display: inline-block;
        }
      </style>
        <div id="div1">Hi</div>
        <div id="div2">This is a Lit </div>


      <button @click="${this.decrement}" aria-label="decrement">-</button>
      <p>value: ${this.val}</p>
      <button @click="${this.increment}" aria-label="increment">+</button></body>
    `;
  }

  decrement() {
    this.val--;
  }

  increment() {
    this.val++;
  }


  updated(props) {
    console.log("generated event", props);
    this.dispatchEvent(new CustomEvent('value-changed', {  bubbles: true, composed: true, detail: {val:this.val} }));

  }
}

customElements.define('x-counter', XCounter);
...