Toggle the visibility of a table column based on user selection in Vue.js

I am having issues with displaying and hiding based on checkbox click events. Can anyone assist in identifying the mistake?

When clicking on an ID, it should hide the ID column. Similarly, clicking on "first" should show/hide based on checkbox clicks, and the same for other fields triggered by checkbox events.

<html>
  <head>
    <title>VueJs Demo Example</title>
    <script src="https://unpkg.com/vue@3"></script>
    </script>
  </head>
  <body>
    <h1 id="app">{{ message }}
      <div v-for="field in fields">
        <input type="checkbox" :disabled="visibleFields.length == 1 && field.visible" :key="field.key" v-model="field.visible" inline />
        <label>{{field.label}}</label>
      </div>
      <tr>
        <th> ID </th>
        <th>first</th>
        <th>last</th>
        <th>age</th>
      </tr>
      <div v-for="item in items" :fields="visibleFields">
        <table>
          <tr>
            <td>{{item.id}}</td>
            <td>{{item.first}}</td>
            <td>{{item.last}}</td>
            <td>{{item.age}}</td>
          </tr>
        </table>
      </div>
    </h1>
    <script>
      const {
        createApp
      } = Vue
      createApp({
        data() {
          return {
            items: [{
              id: 1,
              first: 'Mike',
              last: 'Kristensen',
              age: 16
            }, {
              id: 2,
              first: 'Peter',
              last: 'Madsen',
              age: 52
            }, {
              id: 3,
              first: 'Mads',
              last: 'Mikkelsen',
              age: 76
            }, {
              id: 4,
              first: 'Mikkel',
              last: 'Hansen',
              age: 34
            }, ],
            fields: [{
              key: 'id',
              label: 'ID',
              visible: true
            }, {
              key: 'first',
              label: 'First Name',
              visible: true
            }, {
              key: 'last',
              label: 'Last Name',
              visible: true
            }, {
              key: 'age',
              label: 'Age',
              visible: true
            }, ]
          }
        },
        computed: {
          visibleFields() {
            return this.fields.filter(field => field.visible)
          }
        },
      }).mount('#app')
    </script>
  </body>
</html>

Please let me know if further clarification is needed.

Thank you in advance

Answer №1

Check out the code snippet below (utilizing v-if and a method to determine column visibility):

const app = Vue.createApp({
  data() {
    return {
      items: [{id: 1, first: 'Mike', last: 'Kristensen', age: 16}, {id: 2, first: 'Peter', last: 'Madsen', age: 52}, {id: 3, first: 'Mads', last: 'Mikkelsen', age: 76}, {id: 4, first: 'Mikkel', last: 'Hansen', age: 34}],
      fields: [{key: 'id', label: 'ID', visible: true}, {key: 'first', label: 'First Name', visible: true}, {key: 'last', label: 'Last Name', visible: true}, {key: 'age', label: 'Age', visible: true}]
    }
  },
  computed: {
    visibleFields() {
      return this.fields.filter(field => field.visible)
    }
  },
  methods: {
    isVisible(id) {
      return this.visibleFields.find(v => v.key === id)
    },
  },
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div v-for="(field, i) in fields" :key="i"> 
    <input type="checkbox" :disabled="visibleFields.length == 1 && field.visible" :key="field.key" v-model="field.visible" inline />
    <label>{{ field.label }}</label> 
  </div>
  <table>
    <tr>
      <th v-for="(field, i) in fields" :key="i"> 
        <label v-if="isVisible(field.key)">{{ field.label }}</label> 
      </th>
    </tr>
    <tr v-for="(item, i) in items" :key="i">
      <td v-for="(itm, key, i) in item" :key="i">
        <div v-if="isVisible(key)">{{ itm }}</div>
      </td>
    </tr>
  </table>
</div>

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

Show the Vue.js template in a Laravel Blade view

I have been struggling to integrate a Vue.js component into a Laravel blade file. Despite researching tutorials and Stack Overflow solutions, I have not been able to resolve the issue. Below is the template that I want to display: <template> < ...

Are HTML entities ineffective in innerHTML in javascript?

Take this example: <script type="text/javascript> function showText() { var text = document.getElementById("text-input").value; document.getElementById("display").innerHTML = text; } </script> <?php $text = "<html>some ...

JavaScript having trouble parsing JSON, despite Chrome console being able to parse it flawlessly

I've hit a roadblock while attempting to retrieve coordinates from a database for the Google Maps API in order to create a polygon. First, I fetch my data from the database using Laravel Framework: MapController - public function getallmapcoords(re ...

Tips for Angular4: ensuring ngOnDestroy completion before navigation

My task involves managing a list of objects where the user can choose an object to edit using a child component. However, when the user returns to the list component, the child component needs to clean up in the ngOnDestroy method, which includes making a ...

Unable to recreate the Jquery Mobile Autocomplete demonstration

Attempting to recreate a demo using my own remote data source: The HTML page mirrors the demo, with one change: url: "http://localhost/sample.php", Here is the dummy remote data source sample.php <?php $a = array('apple', 'mango&apo ...

Encountered an error when attempting to load resource: net::ERR_CERT_AUTHORITY_INVALID following deployment on Vercel

I recently deployed a chatUI-app on Vercel that fetches chats from an API located at "http://3.111.128.67/assignment/chat?page=0" While the app worked perfectly in development, I encountered an issue after deploying it on Vercel where it ...

Change the space character ' ' to '-' when a key is lifted

Hey, I need some help with a coding problem. I have two input fields and I want to automatically mirror the text from the first input into the second input field using a keyup jquery function. However, my current setup adds a space whenever I hit the spac ...

How to style large numbers with AngularJS

I'm facing a challenge with large numbers in a table and I'm seeking a solution to format them, ideally as $13b, $10m... Has anyone encountered this issue before and discovered a customized filter or solution for it? Appreciate any help! ...

Implementing event handling with .On() in Jquery following .Off()

I need assistance with my responsive navigation bar. I am having trouble with the jQuery code to disable hover events if the width is less than or equal to 768px and enable it for desktop screens. $(window).on('load resize', function (e) { v ...

Mapping an array of objects using dynamically generated column names

If I have an array of objects containing country, state, city data, how can I utilize the .map method to retrieve unique countries, states, or cities based on specific criteria? How would I create a method that accepts a column name and maps it to return ...

Enable the use of empty spaces in ag-grid filter bars

I'm experiencing an issue with the ag grid filter. It seems to be disregarding white spaces. Is there a way to configure the grid to recognize blank spaces in the filter? Any suggestions for resolving this issue? Where can I find the option to accept ...

Accessing the selected list item from an unordered list in Vue.js

How can I capture the selected item from a dropdown-style list and perform operations based on that selection? In my list, each item is associated with a key for unique identification, except for 'Create New Filter'. I am seeking guidance on ho ...

Creating an endless ticker animation in AngularJS that dynamically adjusts to element dimensions

This is my initial foray into AngularJS, where I am creating a ticker display comprised of boxes. Check out the CodePen here The Code: index.jade: doctype html html(ng-app="ticker") head script(src="../bower_components/angular/angular.js" ...

Creating React components through the use of the map function

Utilizing the hackernews api, I am attempting to extract the "data" property from my response object in order to display each story title individually on the browser. Initially, the data is structured as an array of id's representing individual storie ...

Having trouble initializing an array of objects to store data in MongoDB using AngularJS

I am facing an issue while trying to save dynamically created HTML in MongoDB using Mongoose from AngularJS. The problem lies in creating the required object that matches the Mongoose schema I have defined. model code var SegmentSchema = new Schema({ n ...

Different ways to verify if a Checkbox is selected within a table

As a newcomer to reactjs, I have a component that renders two tables with different data using the same component and passing data through props. Each table has checkboxes for selection. If a user selects items from both tables, I want to detect if they ha ...

"React - encountering issues with state being undefined when passing child state up through parent components

I am currently navigating the world of react and have encountered a hurdle. I find myself facing difficulties in updating the parent component based on changes in the child state. I was able to pass the child state to the parent by linking the child's ...

Error in MongoDB Connection: Timeout issue caused by an unresolved Promise

Issue Overview Whenever I attempt to execute nodemon server, a timeout error is displayed indicating [nodemon] app crashed - waiting for file changes before starting.... Detailed Problem Description I have three files located at the following paths: ...

The slides in Swiperjs are having trouble moving smoothly

I am experiencing some challenges with swiperjs where the slides are not snapping to the next slide and I am unable to fetch the active index from them. Below is a snippet of my code where I am using typescript, swiperjs version 6.84, and the Ionic frame ...

Is a Selenium loop a viable option?

</head> <body> <table cellpadding="1" cellspacing="1" border="1"> <thead> <tr><td rowspan="1" colspan="3">test</td></tr> </thead><tbody> <tr> <td>click& ...