关于聚合物,我如何获得一个网页组件'说'到另一个web组件

With regards to Polymer, How do I get one web component to 'speak' to another web component?

本文关键字:组件 网页 web 另一个 一个 聚合物 何获得      更新时间:2023-09-26

我希望能够在web组件1中填写表格,单击web组件1的提交按钮,然后将数据发布到web组件2中的网格中。Web组件1与Web组件2位于不同的html文件中。

//web component 1
<dom module id="foo-form">
<template>
  <paper-input id="myID" label="ID"value="{{myID}}"></paper-input>
  <paper-button id="submitForm" on-click="submitForm">Submit</paper-button>
</template>
 <script>
  (function() {
    "use strict";
  Polymer({
    is: 'foo-form',
     });
    })();
 </script>
</dom-module>

//Web component 2*
<dom-module id="my-grid">
  <template>
    <vaadin-grid selection-mode="single" id="fooBarGrid" >
      <table>
        <col name="vendorID" sortable="" />
        <thead>
          <tr>
            <th>ID</th>
         </tr>
        </thead>
      </table>
    </vaadin-grid>
  </template>
 <script>
   document.addEventListener("WebComponentsReady", function() {
      // Reference to the grid element.
      var grid = grid || document.querySelector("#fooBarGrid");
      // Reference to the template element
      var template = template || document.querySelector("template");
      // Add some example data as an array.
      var data = [
        { "myId": 0 } 
      ];
      grid.items = data;
 });
  </script>
 <script>
    (function() {
      'use strict';
      Polymer({
          is: 'my-grid',
        });
    })();
  </script>
</dom-module>

基本上有两种方法:

  1. 使用中介模式。如果您有一个同时包含my-gridfoo-form元素的父元素,则此操作效果良好。可以在此处找到解决方案
  2. 如果您想在没有公共父级或不同DOM分支的元素之间进行通信,可以使用iron信号,它提供基本的发布和订阅功能

建议采用解决方案1。