using a button as a header for a column in Vue.js

I am looking to create a clickable button as one of the headers in my table. The table receives its columns from a parent component via an array. In this case, I want to include a button as the last column header.

<BaseTable
        :columns="table.columns"
</BaseTable>
.
.
.
    table: {
       columns: [
          {
            title: "Role",
          },
          {
            title: "No."
          },
          {
            title: "Milestone"
          },
          {
            title: "Status"
          },
          {
            title: "Condition"
          },
          {
            title:
              '<button >+ View all</button>',
          }
        ]
    }

The table component then receives these columns as a prop and displays them like this:

         <tr>
            <th>
                {{ column.title }}
            </th>
          </tr>

Ultimately, the final layout should resemble something like this:https://i.sstatic.net/CpElb.png

Could you advise me on how to achieve this?

Answer №1

Have you considered implementing something like this?

    <th>
      <button v-if="column.isBtn">{{column.title}}</button>
      <template v-else>{{column.title}}</template>
    </th>

Update the last object in your columns array to resemble this:

{
  title: "View all",
  isBtn: true
}

I have simply added a button to the table header column and will only display it when the isBtn property in the column object is set to true.

I hope this code proves useful to you.

Answer №2

One effective way to personalize the display of that cell is by utilizing scoped slots:

Vue.component('BaseTable', {

  props: ['columns', 'data'],

  template: `<table>
<thead>
  <tr >
    <th v-for="(col,i) in columns" :key="i">
     <template  v-if="col.key && $scopedSlots[col.key]" >
        <slot :name="col.key" :column="col"></slot>
     </template>
     <template v-else>
         {{col.title}}
     </template>
    </th> 
       
  </tr>
</thead>
</table>`

})


var app = new Vue({
  el: '#app',

  data: {
    employees: [{
        "id": "1",
        "employee_name": "Tiger Nixon",
        "employee_salary": "320800",
        "employee_age": "61",
        "profile_image": ""
      },
      {
        "id": "2",
        "employee_name": "Garrett Winters",
        "employee_salary": "170750",
        "employee_age": "63",
        "profile_image": ""
      },
      {
        "id": "3",
        "employee_name": "Ashton Cox",
        "employee_salary": "86000",
        "employee_age": "66",
        "profile_image": ""
      },
      {
        "id": "4",
        "employee_name": "Cedric Kelly",
        "employee_salary": "433060",
        "employee_age": "22",
        "profile_image": ""
      },
      {
        "id": "5",
        "employee_name": "Airi Satou",
        "employee_salary": "162700",
        "employee_age": "33",
        "profile_image": ""
      },
      {
        "id": "6",
        "employee_name": "Brielle Williamson",
        "employee_salary": "372000",
        "employee_age": "61",
        "profile_image": ""
      }
    ],
    columns: [{
        title: 'ID',
      },

      {
        title: 'employee name',
      },
      {
        title: 'employee salary',
      },
      {
        title: 'employee age',
      },
      {
        title: 'View All',
        key: 'viewall'
      },
    ]
  },


})
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc8a8999bcced284">[email protected]</a>/dist/vue.js"></script>
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />

<div id="app">
  <base-table :columns="columns">
    <template v-slot:viewall="{col}">
        <button class="btn btn-primary">+View All</button>
     </template>
  </base-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 the reason behind encountering a "Cannot return null for non-nullable field" error while attempting a mutation?

Exploring (Apollo) GraphQL on the server side has presented me with a puzzling issue. I have been attempting to register a user, but I keep encountering the error documented in the linked image below. What could be causing this problem? Let's disregar ...

Convert JavaScript files into JSON files using Laravel

I have a JavaScript file containing key-value pairs as shown below: es.js export default { currency: "Dinero", void: "Vacio", } Now, I need to convert this file into a JSON format. es.json { "currency" : "Dinero", "void" : "Vacio", } W ...

Transform Float32Array into Buffer object

My goal is to retrieve a binary array of floating points. I am using a geotiff library that provides me with a Float32Array, but since the http can only handle strings or buffers, I need to "convert" it into a buffer. const tiff = await geotiff.fromUrl( ...

The act of coming back with just one array

I'm having trouble grasping the concept of returning a single array from a function that calls another function multiple times. The issue I'm facing is that each time the scrapingfunction runs, the console.log in the code provided outputs an arra ...

Invisible reCaptcha: The Unseen AJAX Request

I am having difficulty implementing the invisible reCaptcha on my website. I have followed these steps: header <!-- Invisible reCaptcha --> <script src="https://www.google.com/recaptcha/api.js" async defer></script> form.php <f ...

Is it possible to incorporate vector graphics/icons by simply adding a class to a span element in HTML5?

In order to add a glyphicon icon to our webpage, we simply need to include its class within a span element, as demonstrated here: <span class="glyphicon glyphicon-search"></span> We also have a few files in .ai format that can be converted to ...

Unable to transfer all the formatting from the original file for the window.print() function. Localhost is functioning properly, but encountering issues with production

I'm encountering an issue with getting all styles from my Vue app. I have tried the code provided in this answer: https://stackoverflow.com/questions/52343006/how-to-print-a-part-of-a-vue-component-without-losing-the-style While it works fine on loc ...

Contemplate and send an Axios request directly from the browser's URL bar

Seeking JavaScript Logic Assistance I could use some guidance on implementing JavaScript logic, specifically with Vue Router. I don't necessarily need the answer handed to me, just a nudge in the right direction (and apologies if my question is not q ...

Obtain the registration ID for Android to enable push notifications by utilizing PushSharp

I am currently utilizing the PushSharp library and have come across deviceToken in the sample code provided on this link. Could someone kindly assist me on how to obtain this deviceToken? The PushSharp sample code does not clearly explain this. apnsBrok ...

How can HTML text be displayed based on certain JavaScript conditions?

By modifying the style of the text, I was able to implement basic functionality for validating correct answers. However, my main query is whether it is feasible to display a specific phrase upon achieving a perfect score. Upon analyzing the provided sample ...

Convert require imports to Node.js using the import statement

Currently learning NodeJs and encountering a problem while searching for solutions. It seems like what I am looking for is either too basic or not much of an issue. I am working on integrating nodejs with angular2, which involves lines of code like: impo ...

Issue encountered when attempting to trigger an ionic modal from a custom control in Google Maps

I am facing an issue with my custom Google map control in Ionic framework. I want the control to open a modal when clicked, but I keep getting an error "Cannot read property '$$destroyed' of undefined" when I try to do so. On the other hand, anot ...

Leveraging AngularJS ngBind with a JavaScript object

Within the given string, integrating a javascript object and embedding it into an ngBinding does not result in proper evaluation. I have a string where I want to incorporate a specific part of a javascript object and am transitioning to Angular for its use ...

Tips for adjusting the position of an icon when encountering a line break using Javascript or CSS

After some trial and error, I managed to get it working, but only when the page is initially loaded and not in a responsive manner. Below is the JavaScript code I used. if ( $(".alert-box").height() >= 90 ) { $('.img').css(&apos ...

Guide to incorporating @types/module with the corresponding npm module that has type definitions available

This is an example of a module I am currently utilizing in my project. I have come across TypeScript type definitions for the npm module polylabel, which can be found at https://github.com/mapbox/polylabel. When I run npm install --save @types/polylabel, ...

Issue encountered with ngRoute dependency injection, despite successful loading of angular-route.js.min file

I'm struggling to understand why the module isn't loading properly with ngRoute. Even though I have included angular and angular-route scripts from a CDN, I keep encountering the error Error: $injector:modulerr Module Error <!--Angular--&g ...

Exploring the methods for retrieving and setting values with app.set() and app.get()

As I am granting access to pages using tools like connect-roles and loopback, a question arises regarding how I can retrieve the customer's role, read the session, and manage routes through connect-roles. For instance, when a client logs in, I retrie ...

Update elements based on checkbox selection done through iteration

I am working with an array of objects stored in a state. Each object includes an id, title, and URL. I need to loop through this array and display a div containing a checkbox and an image for each object. When a checkbox is clicked, the corresponding id ...

Access-Control-Allow-Origin does not permit AngularJS Origin http://localhost:8080

I'm working on a web application using AngularJS. It's an admin interface that depends on a json-rpc API hosted on a different domain. When testing in my local environment, I encountered the error "Origin http://localhost:8080 is not allowed by ...

Node.js encountering difficulties with updating files

Struggling with updating my users' points continuously every x amount of seconds. Despite looping through each user, only the last user receives the 10 additional points when it goes through the loop... Any suggestions would be greatly appreciated! s ...