Vue App中的LocalStorage具有多个输入 [英] LocalStorage in Vue App with multiple inputs

查看:46
本文介绍了Vue App中的LocalStorage具有多个输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这是否可行-但我正在Vue应用程序上工作,其中多个输入字段发布到同一列表中-我需要以某种方式存储它,因此当您刷新网站时,输入字段已保存.

i dont know if this is possible - but i am working on a Vue app with multiple input fields that posts to the same list - and i need this to be stored somehow, so when you refresh the site, the outputs from the input fields are saved.

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

This means both the taskList and subTaskList array should be saved ( i know i've only worked on taskList ).

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

The example i posted here saves the data fine, however if you refresh, it will post all the data in all the components, can this be fixed so it will only be in the right components?

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"发布到第一天"组件并刷新页面,它将随后将"Foo"和"Bar"发布到第一天"和第二天". 本质上,我希望能够将示例"Foo"发布到第一天",将"Bar"发布到第二天",然后从那里将"Hello World"发布到购物清单,并且所有这些都将保存在正确的位置,而不是将所有内容都张贴在任何地方.

To be clear, i will come with an example: As it is now, if i post "Foo" and "Bar" to the "Day One" component and refresh the page, it will then post "Foo" and "Bar" to both "Day One" and "Day Two". Essentially, i would like to be able to post for an example "Foo" to "Day One", "Bar" to "Day Two" and from there post "Hello World" to the Shopping List, and it would all be saved in the right places, instead of posting everything everywhere.

顺便说一句:我是后端工作的磨砂膏.

BTW: I'm a scrub at backend work.

推荐答案

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

To persist global state, you may use the plugin vue-persistent-state like this:

import persistentStorage from 'vue-persistent-storage';

const initialState = {
  newTask: "",
  taskList: [],
  newSubTask: "",
  subTaskList: [],    
};
Vue.use(persistentStorage, initialState);

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

Now newTask, taskList, newSubTask and subTaskList is available as data in all components and Vue instances. Any changes will be stored in localStorage, and you can use this.taskList etc. as you would in a vanilla Vue app.

您的列表组件现在变为:

Your list component now becomes:

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);
    },
  },
});

如果您想了解其工作原理,请代码非常简单.基本上是

If you want to understand how this works, the code is pretty simple. It basically

  1. 添加 mixin ,以使initialState在所有Vue实例中均可用,并且
  2. 监视更改并将其存储.
  1. adds a mixin to make initialState available in all Vue instances, and
  2. watches for changes and stores them.

免责声明:我是 vue-的作者持久状态.

这篇关于Vue App中的LocalStorage具有多个输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆