【问题标题】:Can't restoring data from localstorage do not working无法从本地存储恢复数据不起作用
【发布时间】:2019-05-20 19:23:32
【问题描述】:

所以我不能将代码发布到 jsfeedle,这是我的提供程序或 jsfeedle 的问题 - 它不允许我保存代码。所以我在这里发布代码:

<!DOCTYPE html>
<html>
<head>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <title>test</title>

</head>
<body>
    <div id="app">
     <input v-model="message" @keyup.enter.native="pressed">
    </div>

</body>

    <script>
        new Vue({
          el: '#app',
          data: {
            message: ''
          },

            created()
              {
                document.onkeydown=function(e)
                  {
                    var key=window.event.keyCode;
                    if(key==113){
                      console.log('F2 pressed save')
                      localStorage.message = this.message;
                      console.log("recovered value: ", this.message)
                    }

                    if(key==115){
                      console.log('F4 restore')
                      // this.message = localStorage.message;
                      this.message = "444";

                    }

                  }

            }

            })

    </script>

</html>

我无法通过按键(在我的情况下为 F4)恢复保存到本地存储数据的问题。

更新:这里是实时示例https://jsbin.com/wiqezuheji/edit?html,js,output

【问题讨论】:

    标签: vue.js local-storage


    【解决方案1】:

    在 localStorage 中保存和检索变量的方式与您的尝试有些不同。正确的语法是:

    // Get something from the localStorage
    localStorage.getItem('item_name_here');
    
    // Set something in the localStorage
    localStorage.setItem('item_name_here', value);
    
    // Remove something from the localStorage
    localStorage.removeItem('item_name_here');
    
    // Clear the entire localStorage
    localStorage.clear();
    

     

    所以你的情况是

    // Saving the message in the localStorage
    localStorage.setItem('message', this.message);
    
    // Retrieving the message from the localStorage
    this.message = localStorage.getItem('message');
    

     

    更多信息可以关注at the documentation

     

    编辑

    这里以JSFiddle 为例

    这是一个有效的 JS Bin 示例

    【讨论】:

    • 这段代码对你有用吗?你可以尝试在 jsbin.com 上运行它。它对我不起作用。它不是在输入字段上恢复值。
    • @DmitryBubnenkov 我会尝试制作一个 JSFiddle。该代码确实对我有用,因为我在许多项目中使用它
    • @DmitryBubnenkov 我在答案中添加了一个 JSFiddle 和 JSBin 示例
    • T. Dirks,我的代码中有this 关键字的问题。你能帮我修一下吗?我在按键处理程序中创建新范围...
    【解决方案2】:
    document.addEventListener("keydown", function);
    

    试试

    localStorage.setItem('message', this.message);
    

    在localStorage中设置 和

    this.message = localStorage.getItem('message');
    

    从本地存储中获取

    【讨论】:

    • 你能不能用jsfeedle来展示它是如何工作的。我无法让它工作。
    猜你喜欢
    • 1970-01-01
    • 2018-04-26
    • 1970-01-01
    • 1970-01-01
    • 2017-01-05
    • 2015-06-01
    • 2020-06-07
    • 1970-01-01
    • 2017-08-24
    相关资源
    最近更新 更多