Polymer:Uncaught TypeError:this.saveToCache不是函数

时间:2018-03-20 07:14:27

标签: polymer local-storage

我的代码是这样的。它发生错误this.saveToCache不起作用。有人可以帮忙吗?提前谢谢。

<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../bower_components/polymer/polymer-element.html">
<link rel="import" href="shared-styles.html">

<link rel="import" href="../bower_components/iron-localstorage-behavior/iron-localstorage-behavior.html">
<link rel="import" href="../bower_components/paper-button/paper-button.html">

<dom-module id="my-app">
    <template>
        <paper-button on-click="_insertData">Add<paper-button>
    </template>
    <script>
        class MyApp extends Polymer.Element {
            static get is() { return 'my-app'; }
             _insertData(){
                var key = 123;
                var value = Math.random();
                this.saveToCache(key, value).then(() => {
                    alert("Added");
                });
            }
        }

        window.customElements.define(MyApp.is, MyApp);
    </script>
</dom-module>

1 个答案:

答案 0 :(得分:2)

您已经导入了您的行为,iron-localstorage-behavoir,但您似乎并未将其添加到元素中。

由于您使用了类语法,我猜这是Polymer 2.x,因此您可以看到它需要如何完成here

所以你的代码会变成:

<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="../bower_components/polymer/polymer-element.html">
<link rel="import" href="shared-styles.html">

<link rel="import" href="../bower_components/iron-localstorage-behavior/iron-localstorage-behavior.html">

<dom-module id="my-app">
    <template>
        <paper-button on-click="_insertData">Add<paper-button>
    </template>
    <script>
        class MyApp extends Polymer.mixinBehaviors([Polymer.IronLocalStorageBehavior], Polymer.Element) {
            static get is() { return 'my-app'; }
             _insertData(){
                var key = 123;
                var value = Math.random();
                this.saveToCache(key, value).then(() => {
                    alert("Added");
                });
            }
        }

        window.customElements.define(MyApp.is, MyApp);
    </script>
</dom-module>