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

What could be causing the ERROR TypeError in an Angular form where "_co.service.formData" is undefined?

My attempt to create a form in Angular 7 has resulted in an error message: ERROR TypeError: "_co.service.formData is undefined" Here is the HTML code for the component: <form (sumbit)="signUp(form)" autocomplete="off" #form="ngForm"> <div clas ...

Replacing parts in Vue when clicking on an element

I am currently working on a website with a storytelling concept. The idea is that when a user clicks on a certain element, a new layout will be shown - either a full-screen video or an image. After clicking the "next" button, a different content should be ...

Automatically choose radio buttons within an li element in a loop

Hey there, I'm new to SO and this is my first question. As a bit of a newbie, I found this jquery code snippet on another SO answer that I want to use. The function I'm aiming for is the same, but the markup structure in my HTML is different bec ...

What is the best way to increase padding in a Vuetify view element?

I have been attempting to increase the padding of my view by utilizing the "px-5" class on the container within the view. However, I am struggling to achieve the desired amount of padding. What I am aiming for is padding similar to what is shown in this sc ...

Is there a way to utilize the function body onload in jQuery?

I have some code that needs to be fixed. Currently, when I see <body onload="start()" onresize="resize()" onorientationchange="resize()">, I want the following code snippet to work: $("button").click(function(){ $("body").onload = start; or win ...

Convert individual packages within the node_modules directory to ES5 syntax

I am currently working on an Angular 12 project that needs to be compatible with Internet Explorer. Some of the dependencies in my node_modules folder are non es5. As far as I know, tsc does not affect node_modules and starts evaluating from the main opti ...

Is it possible to generate a triangular attachment below a div element?

My designer sent me a unique design and I'm wondering if it's possible to replicate using HTML, CSS, or JavaScript? https://i.stack.imgur.com/spB71.png I believe it can be done with CSS by creating a separate div positioned absolutely under the ...

utilize jQuery and AngularJS to transform a JSON object into a nested JSON structure

Is there a way to convert my current JSON file into a nested JSON structure like the one below? I've attempted various methods (How to convert form input fields to nested JSON structure using jQuery), but I'm not achieving the desired outcome. Ca ...

What is the best method for asynchronously injecting and providing data?

Within my page, I have implemented an asynchronous fetch method to initialize data: async fetch() { const res = await requestApi(this, '/database'); this.sliderData = res.homeSlider; this.modelData = res.model; ... } To pass thi ...

Showing the Datepicker from jQuery right in the middle of the screen

Here's the generated code as default: <div id="ui-datepicker-div" class="ui-datepicker ui-widget ui-widget-content ui-helper- clearfix ui-corner-all ui-datepicker-multi ui-datepicker-multi-2" style="width: 34em; position: absolute; left: ...

Embarking on the GSAP journey

I'm attempting my first animation using GSAP, but no matter what I try, nothing seems to be working. I've even tried using example code without success. Within my PHP file, I have the following code snippet: <head> <script src="https:/ ...

"Troubleshooting why the jQuery Click Function is malfunctioning specifically in

Can someone help me troubleshoot this animate out script? It works fine on chrome, but not on Firefox and I can't seem to figure out why. Any suggestions? The script is designed to animate certain elements when a specific link is clicked. <scrip ...

What is the best method for incorporating a unique style to a v-dialog component in Vuetify following the most recent update?

I'm currently working on a project using vuetify, and I am facing an issue while trying to add a custom class to a v-dialog component. I have tried searching for information on how to do this, but it seems that the prop "content-class" has been deprec ...

Vue.js does not support using nested v-for loops with p tags

I'm facing an issue with nesting 2 v-for loops in Vue.js. It seems simple, but for some reason, it's not working as expected and I can't figure out why. Looping through the users and displaying their names works perfectly. Even extracting t ...

Cannot seem to get VUEJS2.0.0.rc.2 vm.$destroy(true) function to properly execute

When using vuejs2.0.0.rc.2, I encountered an issue where I could not destroy a component with this.$destroy(true) Even though the event listener was removed, the DOM node failed to be removed from the DOM. Check out the live code example here: h ...

Is it possible to arrange a react map based on the length of strings?

I am working on a React function that loops through an object and creates buttons with text strings retrieved from the map. I want to display the text strings in order of their length. Below is the code snippet for the function that generates the buttons: ...

encountering a problem while trying to run `npm install react-native-modal-datetime-picker` in the terminal

I've encountered an issue while working on my app where I keep getting errors when trying to install the react-native-modal-datetime-picker package, as well as other date time picker packages like @react-native-community/datetime-picker The specific ...

Use the button to trigger the opening of the datepicker in React material UI

Currently, I am incorporating a Datepicker in my project using React Material UI. <TextField id="datetime-local" label="Next appointment" type="datetime-local" defaultValue="2017-05-24T ...

Showing the number of times a button has been pressed

I have written some HTML code to create a button and now I am looking for guidance on how I can use Vue.js to track how many times the button has been clicked. Here is what I have so far: <div class="123"> <button id = "Abutton&q ...

Having trouble rendering the React app; encountered an error: JSX contents are unterminated

I am currently facing an issue while trying to fetch data from an API in React using Axios. How can I ensure that useEffect functions properly? My objective is to create a page by fetching data from an API in React through Axios. I have designed a compon ...