【问题标题】:LocalStorage in Vue App with multiple inputs具有多个输入的 Vue App 中的 LocalStorage
【发布时间】:2018-03-17 05:04:45
【问题描述】:

我不知道这是否可能——但我正在开发一个具有多个输入字段的 Vue 应用程序,这些输入字段发布到同一个列表——我需要以某种方式存储它,所以当你刷新网站时,来自输入字段已保存。

这意味着 taskList 和 subTaskList 数组都应该被保存(我知道我只在 taskList 上工作过)。

我在此处发布的示例可以很好地保存数据,但是如果您刷新,它将发布所有组件中的所有数据,是否可以修复此问题,使其仅在正确的组件中?

const STORAGE_KEY = 'madplan-storage'

Vue.component('list-component', {
            data: function() {
                return {
                    newTask: "",
                    taskList: [],
                    newSubTask: "",
                    subTaskList: [],
                };
            },

            created() {
              this.taskList = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');
            },

            template:
                '<div>' +

                '<section class="prefetch">' +
                '<input  v-if="showInput" class="input typeahead" type="text" placeholder="Tilføj ret til madplanen" v-model="newTask" v-on:keyup.enter="addTask">' +
                '</section>' +

                '<details open v-for="task in taskList" v-bind:key="task.text" class="sub-list-item">' +
                '<summary>{{ task.text }}<i class="fa fa-times" aria-hidden="true" v-on:click="removeTask(task)"></i>' + '</summary>' +
                '<input class="subInput" type="text" placeholder="Tilføj til indøbsseddel" v-model="newSubTask" v-on:keyup.enter="addSubTask">' +
                '</details>' +

                '</div>',

            computed: {
                showInput: function() {
                    return !this.taskList.length
                },
            },

            methods: {
                //addTasks
                //
                addTask: function() {
                    var task = this.newTask.trim();
                    if (task) {
                        this.taskList.push({
                            text: task
                        });
                        this.newTask = "";
                        localStorage.setItem(STORAGE_KEY, JSON.stringify(this.taskList));
                    }
                },

                addSubTask: function() {
                    var task = this.newSubTask.trim();
                    if (task) {
                        this.subTaskList.push({
                            text: task
                        });
                        this.newSubTask = "";
                        this.$emit('addedtask', task);
                        localStorage.setItem(STORAGE_KEY, JSON.stringify(this.subTaskList));
                    }
                },

                //removeTasks
                //
                removeTask: function(task) {
                    var index = this.taskList.indexOf(task);
                    this.taskList.splice(index, 1);
                },
            },
        });



        new Vue({
            el: "#madplan",
            data: {
                newTask: "",
                taskList: [],
                newSubTask: "",
                subTaskList: [],
            },
            methods: {
              acknowledgeAddedTask: function(cls, task) {
                this.$data.subTaskList.push({
                	text: task,
                  class: "list-item " + cls
                  })
              },
              acknowledgeRemovedTask: function(task) {
                this.$data.subTaskList = this.$data.subTaskList.filter(it => it.text != task.text)
              },
              removeSubTask: function(task) {
                  var index = this.subTaskList.indexOf(task);
                  this.subTaskList.splice(index, 1);
              },
            }
        });
    <section id="madplan" class="section-wrapper">

        <section class="check-list">
          <div id="mandag" class="dayWrapper">
            <h1>Day One</h1>
            <list-component
              class="mandag"
              v-on:addedtask='task => acknowledgeAddedTask("mandag", task)'
            ></list-component>
          </div>

          <div id="tirsdag" class="dayWrapper">
            <h1>Day Two</h1>
            <list-component
              class="tirsdag"
              v-on:addedtask='task => acknowledgeAddedTask("tirsdag", task)'
            ></list-component>
          </div>
          
        <ul id="indkobsseddel">
            <h2>Shopping List</h2>
            <li v-for="task in subTaskList" v-bind:key="task.text" :class="task.class">{{ task.text }}<i class="fa fa-times" aria-hidden="true" v-on:click="removeSubTask(task)"></i></li>
        </ul>

     </section>
     
     <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://unpkg.com/vue/dist/vue.js" charset="utf-8"></script>

为了清楚起见,我将举一个例子: 就像现在一样,如果我将“Foo”和“Bar”发布到“Day One”组件并刷新页面,它会将“Foo”和“Bar”发布到“Day One”和“Day Two”。 本质上,我希望能够将示例“Foo”发布到“第一天”,将“酒吧”发布到“第二天”,然后从那里发布“Hello World”到购物清单,所有内容都将保存在正确的地方,而不是到处张贴。

顺便说一句:我是后端工作的磨砂人。

【问题讨论】:

    标签: vue.js local-storage


    【解决方案1】:

    要保持全局状态,您可以像这样使用插件vue-persistent-state

    import persistentStorage from 'vue-persistent-storage';
    
    const initialState = {
      newTask: "",
      taskList: [],
      newSubTask: "",
      subTaskList: [],    
    };
    Vue.use(persistentStorage, initialState);
    

    现在 newTasktaskListnewSubTasksubTaskList 可作为所有组件和 Vue 实例中的数据使用。任何更改都将存储在 localStorage 中,您可以像在普通 Vue 应用程序中一样使用 this.taskList 等。

    您的列表组件现在变为:

    Vue.component('list-component', {
      // data removed
      // created removed
    
      template:
        '<div>' +
    
        '<section class="prefetch">' +
        '<input  v-if="showInput" class="input typeahead" type="text" placeholder="Tilføj ret til madplanen" v-model="newTask" v-on:keyup.enter="addTask">' +
        '</section>' +
    
        '<details open v-for="task in taskList" v-bind:key="task.text" class="sub-list-item">' +
        '<summary>{{ task.text }}<i class="fa fa-times" aria-hidden="true" v-on:click="removeTask(task)"></i>' + '</summary>' +
        '<input class="subInput" type="text" placeholder="Tilføj til indøbsseddel" v-model="newSubTask" v-on:keyup.enter="addSubTask">' +
        '</details>' +
    
        '</div>',
    
      computed: {
        showInput: function() {
          return !this.taskList.length
        },
      },
    
      methods: {
        //addTasks
        //
        addTask: function() {
          var task = this.newTask.trim();
          if (task) {
            this.taskList.push({
              text: task
            });
            this.newTask = "";
            // localStorage.setItem not needed
          }
        },
    
        addSubTask: function() {
          var task = this.newSubTask.trim();
          if (task) {
            this.subTaskList.push({
              text: task
            });
            this.newSubTask = "";
            // $emit not needed, state is global and shared
            // localStorage.setItem not needed
          }
        },
    
        //removeTasks
        //
        removeTask: function(task) {
          var index = this.taskList.indexOf(task);
          this.taskList.splice(index, 1);
        },
      },
    });
    

    如果您想了解其工作原理,the code 非常简单。基本上是

    1. 添加 mixin 以使 initialState 在所有 Vue 实例中可用,并且
    2. 监视更改并存储它们。

    免责声明:我是vue-persistent-state的作者。

    【讨论】:

      猜你喜欢
      • 2017-06-08
      • 1970-01-01
      • 1970-01-01
      • 2019-03-06
      • 1970-01-01
      • 2013-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多