Polymer 2.0如何声明可在其他组件模板中调用的全局函数?
这个问题的核心原因是Polymer的模板绑定只会查找组件实例自身的属性和方法,你定义的全局format函数不在组件的作用域内,所以模板渲染时找不到它;而组件script标签里能调用是因为那里可以访问全局window作用域。
下面给你两种靠谱的解决方法,推荐第一种来避免重复代码:
方法1:用Behavior实现可复用的格式化方法(推荐)
Behavior是Polymer里用来复用组件逻辑的最佳方式,正好适合你这种要在多个组件里用同一个格式化函数的场景。
首先创建一个DateFormatBehavior.html文件:
<link rel="import" href="../bower_components/polymer/polymer-element.html"> <script src="../bower_components/moment/moment.js"></script> <script> const DateFormatBehavior = { methods: { format(date) { return moment(date).format('dddd, D MMMM YYYY'); } } }; </script>
然后在需要用到这个方法的组件里,导入Behavior并添加到组件的behaviors数组中:
<link rel="import" href="./DateFormatBehavior.html"> <!-- 根据你的实际路径调整 --> <dom-module id="my-event-component"> <template> <!-- 现在模板里可以直接调用format方法了 --> <strong>[[format(event.date)]]</strong> </template> <script> class MyEventComponent extends Polymer.Element { static get is() { return 'my-event-component'; } static get behaviors() { return [DateFormatBehavior]; } } customElements.define(MyEventComponent.is, MyEventComponent); </script> </dom-module>
这样所有需要格式化日期的组件,只要导入这个Behavior就能直接用format方法,完全不用重复定义。
方法2:在单个组件内直接定义方法
如果只有少数组件需要这个格式化逻辑,也可以直接在组件类里定义format方法:
<link rel="import" href="../bower_components/polymer/polymer-element.html"> <script src="../bower_components/moment/moment.js"></script> <dom-module id="my-single-component"> <template> <strong>[[format(event.date)]]</strong> </template> <script> class MySingleComponent extends Polymer.Element { static get is() { return 'my-single-component'; } format(date) { return moment(date).format('dddd, D MMMM YYYY'); } } customElements.define(MySingleComponent.is, MySingleComponent); </script> </dom-module>
为什么原来的方式不行?
你之前在moment.html里定义的format是全局函数(挂载在window对象上),但Polymer模板的绑定上下文是当前组件的实例,不是全局的window。所以模板里的[[format(event.date)]]会去组件实例上找这个方法,找不到就会抛出"method 'format' not defined"的错误。而你在组件的script标签里能调用,是因为script代码在全局作用域下可以访问window.format。
内容的提问来源于stack exchange,提问作者yberg
相关产品推荐
相关产品推荐

