【问题标题】:Polymer: How to use imported function in computed binding聚合物:如何在计算绑定中使用导入函数
【发布时间】:2017-09-11 06:21:11
【问题描述】:

我想为不同自定义元素中的计算绑定使用共享函数。这可能吗?

无论我如何导入共享函数,都会出现控制台错误:

method `formatAmount` not defined

计算的绑定类似于:

<span>[[formatAmount(amount)]]</span>

我尝试在元素上方使用标签。我在元素内部尝试过。我已经在 index.html 中尝试过。

是否所有计算绑定方法都需要在自定义元素中定义且不能共享?我必须使用 mixin 吗?

更新:我创建了一个丑陋的工作,我在我的自定义元素上定义了一个调用共享方法的私有方法。然后在计算绑定中使用私有方法。由于额外的样板,这很难看。

...
<script src="format-amount.js"></script>

<dom-module id="my-foo">
  <template>
    ...[[_formatAmount(amount)]]...
  </template>
  <script>
    class MyFoo extends Polymer.Element {
      ...
      _formatAmount(amount) {
        return formatAmount(amount); // Defined in format-amount.js.
      }
    }
  </script>
</dom-module>

【问题讨论】:

    标签: polymer polymer-2.x


    【解决方案1】:

    这与我几个月前所问的question 类似。

    您可以使用mixin。 mixin 只是一个接受类并返回子类的函数。如果你想了解更多click here。

    对于您的问题,请在单独的 html 文件中定义 mixin - my-mixin.html:

    const MyMixin = (superClass) => class extends superClass {
    
        constructor() {
          super();          
        }
    
        formatAmount(amount) {
          //function contents  
        }
    
    }
    

    然后在你的元素中导入并添加 mixin:

    &lt;link rel="import" href="my-mixin.html"&gt;

    class MyFoo extends MyMixin(Polymer.Element)

    然后你可以简单地从你的元素中调用函数:

    <template>
      ...[[formatAmount(amount)]]...
    </template>
    

    要访问脚本中的函数,请使用super.formatAmount(amount)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-23
      • 2015-01-29
      • 1970-01-01
      • 2017-02-14
      • 1970-01-01
      • 1970-01-01
      • 2018-01-13
      • 1970-01-01
      相关资源
      最近更新 更多