Search code examples
javascriptvue.jscookiesbootstrap-vue

How to remember input field contents for this BootstrapVue table?


I have a BootstrapVue table below;

enter image description here

Here is the code, thanks to this answer;

new Vue({
  el: '#app',
  data() {
    return {
      filter: '',
      items: [
        { id: 1, first_name: "Mikkel", last_name: "Hansen", age: 54 },
        { id: 2, first_name: "Kasper", last_name: "Hvidt", age: 42 },
        { id: 3, first_name: "Lasse", last_name: "Boesen", age: 39 },
        { id: 4, first_name: "Kasper", last_name: "Hansen", age: 62 },
        { id: 5, first_name: "Mads", last_name: "Mikkelsen", age: 31 },
      ]
    }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.js"></script>
<script src="https://unpkg.com/bootstrap-vue@2.6.1/dist/bootstrap-vue.min.js"></script>

<link href="https://unpkg.com/bootstrap-vue@2.6.1/dist/bootstrap-vue.css" rel="stylesheet" />
<link href="https://unpkg.com/bootstrap@4.4.1/dist/css/bootstrap.min.css" rel="stylesheet" />

<div id="app" class="p-5">
  <b-input v-model="filter" placeholder="Filter table.."></b-input>
  <hr />
  <b-table :items="items" :fields="fields" :filter="filter">
  </b-table>
</div>

Basically, the input form is used for filtering purposes.

How can the contents used in this input form be remembered so that if the user closes the page and opens the page next time, the past contents for this filter input form can be loaded automatically? Are cookies the most straightforward way to do it? I am open to any way to implement this memory feature.

I am using BootstrapVue, vue.js 2.6


Solution

  • You can use window.localStorage, and bind it to your filter input.

    For example:

    data: () => ({
      filter: localStorage.getItem('searchValue') || '',
    }),
    watch: {
      filter() {
        localStorage.setItem('searchValue', this.filter)
      }
    }
    
    <b-input v-model="filter" placeholder="Filter table.."></b-input>