Display and conceal table columns dynamically in Vue by utilizing the Vuetify data table functionality

Looking for an example:

How to show hide columns of vuetify data table using v-select list

I have created something similar, but I'm facing an issue where the table doesn't refresh when changing the header data:

https://codepen.io/Meff1/pen/vYLNYWR

<template>
  <v-container>
    <v-select v-model="value" :items="headers" label="Select Item" multiple return-object>
      <template v-slot:selection="{ item, index }">
        <v-chip v-if="index === 0">
          <span>{{ item.text }}</span>
        </v-chip>
        <span v-if="index === 1">(+{{ value.length - 1 }} others)</span>
      </template>
    </v-select>
    <br />
    <v-data-table :headers="this.selectedHeaders" :items="xyz">
      <template slot="items" slot-scope="props">
        <td
          v-for="header in this.selectedHeaders"
          :key="header"
          v-show="show[header.text]"
        >{{ props.item[header.value] }}</td>
      </template>
    </v-data-table>
  </v-container>
</template>


<script lang="ts">
const charData: Array<object> = [
  {
    id: 10,
    firstName: "Kyle",
    lastName: "Broflovski",
    saying: "Goddamnit Cartman!"
  },
  {
    id: 20,
    firstName: "Eric",
    lastName: "Cartman",
    saying: "Screw you guys, Im going home"
  },
  {
    id: 30,
    firstName: "Stanley",
    lastName: "Marsh",
    saying: "WTF"
  },
  {
    id: 40,
    firstName: "Kenny",
    lastName: "McCormick",
    saying: "hmhpmhphmphmhp"
  }
];

let headers: Array<object> = [];
let selectedHeaders: Array<object> = [];
const show: any = {};
const value: Array<object> = [];
let selectedData: Array<object> = [];

import Vue from "vue";

export default Vue.extend({
  name: "PFTable",
  data: () => ({
    charData,
    headers,
    value,
    selectedHeaders,
    selectedData,
    show
  }),

  computed: {
    xyz: () => {
      return selectedData;
    }
  },

  watch: {
    value(val) {
      selectedHeaders = val;

      const res = selectedHeaders.map(x => x.text);
      selectedData = [];

      for (const k in charData) {
        const element: any = charData[k];

        const filtered = Object.keys(element)
          .filter(key => res.includes(key))
          .reduce((obj: any, key: any) => {
            obj[key] = element[key];
            return obj;
          }, {});

        selectedData.push(filtered);
      }
    }
  },

  beforeCreate() {
    headers = [];
    const headersData = Object.keys(charData[0]);

    headersData.forEach(element => {
      headers.push({ text: element, value: element });
    });

    selectedHeaders = headers;
    selectedData = charData;
  }
});
</script>

I am struggling to figure out how to toggle the visibility of columns based on selections made in the select list.

I have an array called selectedData which is linked to the data table as its items property. selectedData is a computed property and gets updated in the watcher method when changes are made to the select list. However, the data table does not reflect these changes. Shouldn't the computed property re-evaluate whenever the underlying property changes?

Answer №1

It seems like the reference to this.selectedHeaders may be lost in your watcher after assigning a value to your selectedHeaders variable in the outa scope. This could explain why your template is not updating as expected.

Consider changing the code from:

watch: {
   value(val) {
      selectedHeaders = val;

To:

     selectedHeaders.splice(0).push(...val) 

Alternatively, you can try:

     this.selectedHeaders = val

Answer №2

Make sure to set up your data in the data() function

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display Default Image in Vue.js/Nuxt.js when Image Not Found

I'm currently working on implementing a default image (placeholder image) for situations where the desired image resource is not found (404 error). I have a dictionary called article which contains a value under the key author_image. Although the stri ...

When iterating through a table, an error occurs stating that the property "rows" is not available on type HTMLElement (

Issue Error TS2339 - Property 'rows' does not exist on type HTMLElement when looping through table in Angular 7 Encountering error when trying to loop through HTML table in Angular 7 Currently working with Angular 7 and facing an error while ...

Access to this feature is restricted when using a decorator in TypeScript with NodeJS

I have designed a decorator to handle async errors, but I am encountering difficulties in accessing it within class methods. My goal is to develop a reusable CRUD class that other classes can inherit from, with a method for CRUD operations. Decorator Code ...

Saving a local JSON file in Angular 5 using Typescript

I am currently working on developing a local app for personal use, and I want to store all data locally in JSON format. I have created a Posts Interface and an array with the following data structure: this.p = [{ posts:{ id: 'hey man&ap ...

Error message pops up in WebStorm when attempting to access the map object in Angular

Within one of the services in my Angular application, I have utilized the map() function to retrieve data from the GitHub API. getUser(username: string) { // Regular Expression used for String Manipulation return this.http.get('https://api.github.com ...

Is there a comparison you can make between v-for and a similar feature in Stencil? (such as a functionality akin to v-for

When working with arrays in Stencil, I need to repeat a specific element multiple times based on the array. In Vue, I typically use v-for for this purpose, but what is the equivalent in Stencil? ...

Why aren't my arrays' characteristics being recognized when I create an instance of this class?

There is a puzzling issue with the arrays in my class. Despite creating them, when I try to access them in another class they are not recognized, only the otherProp is visible. To make matters worse, attempting to add elements to the arrays results in an ...

I possess a function that can retrieve the key of an Object, but now I am faced with the task of accessing the actual Object using this value in JavaScript

This is my first time seeking advice on a technical issue. I'm currently working with the following function: export function sendRequest<T>(req: RawRequest, options) { const start = Date.now(); const reqOptions: CoreOptions = { ...

Loading data in advance with vuex and vue-resource

I'm currently in the process of developing an application based on this particular structure: http://vuex.vuejs.org/en/structure.html Within my components/App.vue file, the layout is as follows: <template> <div id="app"> <course :co ...

"Encountered an issue with Next-Auth session returning as undefined in getServerSideProps using NextJS version 13.2

When inspecting the code below, session is found to be undefined upon logging from the client side after being transferred from getServerSideProps. import { getServerSession } from 'next-auth/next'; import { authOptions } from './api/auth/[. ...

TSLint throws an error, expecting either an assignment or function call

While running tslint on my angular project, I encountered an error that I am having trouble understanding. The error message is: expected an assignment or function call getInfoPrinting() { this.imprimirService.getInfoPrinting().subscribe( response => ...

Tips on connecting the endpoints of two parallel quadratic Bezier curves that both begin with a MoveTo command

I am currently working on creating a Sankey Diagram from scratch using VueJS and SVG. I have encountered challenges in closing the paths of two parallel quadratic Bezier curve paths from nodes to nodes. For instance, after some additional calculations, I ...

Issues with Angular 4 Rxjs subject subscription functionality

My application consists of a shared service named data.service.ts, which contains the following code: public pauseProjectTask$: Subject<any> = new Subject<any>(); pauseTaskProject(taskData, type){ this.pauseProjectTask$.next(taskData); ...

What should we name the type parameter?

After familiarizing myself with Typescript and understanding the concept of generic type T, I encountered an issue with a simple example. Can you pinpoint what's wrong? function test1<string>(x:number):boolean{ let s:string="hello"; if ...

Retrieve recently appended DOM elements following the invocation of createComponent on a ViewContainerRef

I have a current function in my code that dynamically creates components and then generates a table of contents once the components are added to the DOM. This service retrieves all h3 elements from the DOM to include in the table of contents: generateDy ...

Geolocation plugin in Ionic encountered an issue: "Geolocation provider not found"

I've been working on implementing geolocation in my ionic2 hello world project, and I successfully added the ionic plugin called "Geolocation" by following the instructions on the official website. After running these two commands: $ ionic plugin add ...

Utilize the search component multiple times within a single template in Vue.js

I have a regular search input that searches and displays results effectively. Now, I need to duplicate this search input and reuse it within the same component. <input class="search ml-2" type="search" placeholder="Search" v-model="search"> Here is ...

What is the best way to utilize imported classes, functions, and variables within an Angular 2 template?

I've come up with a solution for incorporating static content into a template, but I'm unsure if it's the best approach. I would like to know if there is an official or more efficient method of achieving this. Here's an example showcas ...

The Angular translation service may encounter issues when used on different routes within the application

I'm currently working on an Angular application that has multi-language support. To better organize my project, I decided to separate the admin routes from the app.module.ts file and place them in a separate file. However, after doing this, I encounte ...

Nest is unable to resolve the dependencies of the ItemsService. Ensure that the required argument at index [0] is present within the AppModule context

After following the Nest JS Crash tutorial from a Youtube Link, I encountered an error when importing an interface in the service. Nest seems unable to resolve dependencies of the ItemsService. It's important to ensure that the argument at index [0 ...