[Vuejs]-Toggle show/hide table column and save to localstorage in vue

0👍

For this you need to set defaults so that the checkbox values first try to read from localStorage. Then create a method when the input is clicked to change the value and update the value set into storage.

Vue.use(VueTables.ClientTable);

new Vue({
    el: "#app",
    data: {
        columns: ['name', 'code'],
        columnHidden: {
            name: localStorage.getItem('name') || false,
            code: localStorage.getItem('code') || false
        },
        data: getData()
    },
    methods: {
        toggleColumn(column) {
            this.columnHidden[column] = !this.columnHidden[column];
            localStorage.setItem(column, true);
        }
    }
});

function getData() {
    return [{
        code: "ZW",
        name: "Zimbabwe"
    }, {
        code: "ZM",
        name: "Zambia"
    }, {
        code: "YE",
        name: "Yemen"
    }];
}
<div id="app" v-cloak>
  <template v-for="column in columns">
    <label for=`toggleTable${column}`>{{`Toggle ${column}`}}</label>
    <input v-on:click="toggleColumn(column)" id=`toggleTable${column}` type="checkbox" :checked="columnHidden[column]" />
    <br />
  </template>

  <v-client-table :columns="columns" v-model="data">
  </v-client-table>
</div>

Leave a comment