【问题标题】:Toggling button issue in polymer聚合物中的切换按钮问题
【发布时间】:2021-03-10 11:39:09
【问题描述】:

我正在尝试使用按钮切换消息的显示。 下面是我的代码。

class DisplayMessage extends PolymerElement {
  // DO YOUR CHANGES HERE
  static get template() {
    return html`
      <style>
        :host {
          display: block;
        }
      </style>

      <h2>Hello [[prop1]]!</h2>
      <button on-click="toggle">Toggle Message</button> <br />
      <template is="dom-if" if="{{user.authorise }}">
        <br />
        <span>I should now display message.</span>
      </template>
    `;
  }

  toggle() {
    // DO YOUR CHANGES HERE
    // hint: use set method to do the required changes
    
    //console.log(this.user);
    //this.user = !this.user
  }

  static get properties() {
    return {
      prop1: {
        type: String,
        value: 'user',
      },
      user: {
        type: Object,
        value: function () {
          return { authorise: false}; // HINT: USE BOOLEAN VALUES TO HIDE THE MESSAGE BY DEFAULT
        },
        notify: true,
      },
    };
  }
}

window.customElements.define('display-message', DisplayMessage);

我试着思考了几个小时,但无法解决。她的要求是单击按钮,单击处理程序切换应将用户属性中的授权值更改为 true。并再次单击为 false 等等。我需要在切换方法中使用 set 方法。我不知道如何做到这一点。请帮我解决这个问题。

提前致谢。

【问题讨论】:

    标签: javascript web-component es6-class polymer-3.x dom-if


    【解决方案1】:

    为什么要为这么小的组件使用库/依赖项,可以使用本机代码完成

    <display-message id=Message name=Cr5>You are authorized</display-message>
    <script>
      customElements.define("display-message", class extends HTMLElement {
        static get observedAttributes() {
          return ["name", "authorized"]
        }
        connectedCallback() {
          this.innerHTML = `<h2>Hello <span>${this.getAttribute("name")}</span></h2><button>Toggle message</button><br><div style=display:none>${this.innerHTML}</div>`;
          this.querySelector('button').onclick = () => this._toggle();
        }
        _toggle(state) {
          let style = this.querySelector('div').style;
          style.display = state || style.display == "none" ? "inherit" : "none";
          this.toggleAttribute("authorized", state);
          console.log(Message.name, Message.authorized);
        }
        get name() { return this.getAttribute("name") }
        set name(value) {
          this.querySelector('span').innerHTML = value;
          this.setAttribute("name", value);
        }
        get authorized() { return this.hasAttribute("authorized")   }
        set authorized(value) { this._toggle(value) }
        
        attributeChangedCallback(name, oldValue, newValue) {
          if (oldValue) this[name] = newValue;
        }
      })
      Message.name = "Cr5";
      Message.authorized = true;
    </script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多