[Vuejs]-LocalStorage in Vue App with multiple inputs

0👍

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

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. adds a mixin to make initialState available in all Vue instances, and
  2. watches for changes and stores them.

Disclaimer: I’m the author of vue-persistent-state.

Leave a comment