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

`Database Schema Enforcement in Firestore: Custom Objects vs Security Rules`

Firestore, being a noSQL database, is schemaless. However, I want to ensure that the correct data type is being passed in. Custom Objects As per Firebase documentation, https://firebase.google.com/docs/firestore/manage-data/add-data class City { const ...

Vue.js Element UI dialog box

Is there a method to customize the close button in el-dialog and replace it with my own design? For instance, can I change the default close button located at the top left corner of the dialog? <el-dialog title="Tips" :visible.sync=" ...

What is preventing absolute paths from functioning properly in TurboRepo?

After setting up a fresh project on the most recent version of TurboRepo, I ventured into the 'apps' directory and established a new Vite project using the 'react-swc-ts' template. Making tweaks to the 'tsconfig.json' file wit ...

Implementing Typescript for React Navigation: Configuring navigationOptions effectively

Within a React Native app utilizing React Navigation, I am working on a screen component where I aim to set the title based on given parameters using the navigationOptions property like so: static navigationOptions = ({navigation}) => ({ title: nav ...

Having trouble with ngx-pagination's next page button not responding when clicked?

I am experiencing issues with pagination. The next page button does not function as expected, and clicking on the page number also does not work. Below is the code snippet and a Demo link for your reference. HTML <table mat-table [dataSou ...

What is the best way to manage events within datalist options using Vue.js?

I have a specific requirement where I need to implement a feature in my data list. When a user selects an option from the datalist, I must update other input fields based on that selection. Below is the code snippet for my input field and Datalist: <i ...

Having trouble opening a JPEG file that was generated using the Writefile Api in Ionic-Cordova

Currently, I am using the writeFile API to create a JPEG image. The process is successful and the image is stored in the directory as expected. However, when I try to open the file manually from the directory, I encounter an error message saying "Oops! Cou ...

The variable 'key' is declared in the Google Chrome extension V3 local storage, but it appears that its assigned value is never actually accessed

In my TypeScript code, I have defined a function like so: setLocalStorage: async (key: string, value: string): Promise<string> => { return new Promise((resolve, reject) => { chrome.storage.local.set({ key: value }, funct ...

Encountering a TS2307 error while trying to import external modules into a TypeScript file

I recently added a new module using npm and now I'm trying to use it in my typescript file. npm install marker-animate-unobtrusive --save import SlidingMarker = require('marker-animate-unobtrusive'); Unfortunately, when I try to access th ...

Uploading multiple images with base64 using Laravel and Vue.js: A comprehensive guide

When attempting to upload multiple images in base64 format, I noticed that only the second image gets uploaded. Is there a simpler way to upload images using laravel and VueJS instead of using base 64? Here is an example of the VueJS method: updateIMG(e) ...

Securing Your Laravel and Vue Application with Sanctum: Handling Unauthenticated Users

After attempting two different approaches to implement Laravel Sanctum for authentication in my Laravel 7/Vue SPA, I encountered the same issue. The methods I tried are: https://dev.to/aschmelyun/authenticating-a-vue-spa-is-easy-with-laravel-sanctum-392a ...

Guide to creating a function and exporting it to a component in react with the help of typescript

I have a ParentComponent where I need to integrate a function from a separate file and incorporate it into the ParentComponent. The structure of the ParentComponent is as follows: function ParentComponent() { const count = 5; // this value usually co ...

Retrieve the element referred to as $el within a computed property

When attempting to retrieve this.$el.offsetTop within a computed property, the following error occurs: Cannot read property 'offsetTop' of undefined Is there a way to access the component's offsetTop in a computed method? If not, what is t ...

Is there a way to determine the quantity of lines within a div using a Vue3 watcher?

Is it feasible to determine the number of text lines in a div without line breaks? I am looking to dynamically display or hide my CTA link based on whether the text is less than or equal to the -webkit-line-clamp value: SCRIPT: const isExpanded = ref(true ...

Is it feasible to alter the file name while utilizing express-fileUpload library?

Is there a way to modify the file name of an uploaded file on the server side? app.post(URL, (req, res) => { let fileName = req.files.file.name; req.fileUpload; res.statusCode = HTTP_OK; res.send("Good Job") }) The settings I have in uploadF ...

Unlocking the Secrets of AnimatedInterpolation Values

I have a question about how to access the value of an AnimatedInterpolation in react-native without resorting to calling private code. To achieve this, I first create an animated value and then wrap it in an interpolation like so: animated = new Anima ...

The Nuxt.config.js file is responsible for rendering the noscript innerHtml element as it appears in

I've stopped JavaScript in my browser settings Incorporated inner HTML for noscript tag in nuxt.config.js Anticipated outcome is to have an iframe element added inside the body, but it's displaying text instead. How can we insert it as an eleme ...

Exploring Vue Slots: A guide to parsing and rendering slot components

Currently facing a challenge while developing a web page using Vue, specifically with parsing and rendering the child components inside the <slot>. I need to extract the slot content, convert it into an array of components, and display these compo ...

registering a back button action in Ionic2 for multiple pages

Currently, I am in the process of developing my Ionic2 app and have encountered a dilemma regarding the functionality of registerBackButtonAction. On one page, let's call it pageA, I have implemented this function and everything is functioning as exp ...

A guide on incorporating Union Types in TypeScript

Currently utilizing typescript in a particular project where union types are necessary. However, encountering perplexing error messages that I am unsure how to resolve. Take into consideration the type definition below: type body = { [_: string]: | & ...