Making a column in a Vue data grid return as a clickable button

My goal is to utilize vue.js grid to display multiple columns with calculated text values, along with a clickable column at the end that triggers a dynamic action based on a parameter (such as calling an API in Laravel).

However, when I include the last column as a clickable link, vue.js displays the HTML tag instead of rendering it within the grid. What am I missing here? VueCode:

  // register the grid component
    Vue.component('demo-grid', {
      template: '#grid-template',
      props: {
        data: Array,
        columns: Array,
        filterKey: String
      },
      data: function () {
        var sortOrders = {}
        this.columns.forEach(function (key) {
          sortOrders[key] = 1
        })
        return {
          sortKey: '',
          sortOrders: sortOrders
        }
      },
      computed: {
        filteredData: function () {
          var sortKey = this.sortKey
          var filterKey = this.filterKey && this.filterKey.toLowerCase()
          var order = this.sortOrders[sortKey] || 1
          var data = this.data
          if (filterKey) {
            data = data.filter(function (row) {
              return Object.keys(row).some(function (key) {
                return String(row[key]).toLowerCase().indexOf(filterKey) > -1
              })
            })
          }
          if (sortKey) {
            data = data.slice().sort(function (a, b) {
              a = a[sortKey]
              b = b[sortKey]
              return (a === b ? 0 : a > b ? 1 : -1) * order
            })
          }
          return data
        }
      },
      filters: {
        capitalize: function (str) {
          return str.charAt(0).toUpperCase() + str.slice(1)
        }
      },
      methods: {
        sortBy: function (key) {
          this.sortKey = key
          this.sortOrders[key] = this.sortOrders[key] * -1
        }
      }
    })

    // bootstrap the demo
    var demo = new Vue({
      el: '#demo',
      data: {
        searchQuery: '',
        gridColumns: ['name', 'power','report'],
        gridData: [
          { name: 'Chuck s', power: Infinity },
          { name: 'Bruce Lee', power: 9000 },
          { name: 'Jackie Chan', power: 7000 },
          { name: 'Jet Li', power: 8000 ,report: '<a href="http://www.google.com>Google</a>"'}
        ]
      }
    })

HTML file:

<script type="text/x-template" id="grid-template">
  <table>
    <thead>
      <tr>
        <th v-for="key in columns"
          @click="sortBy(key)"
          :class="{ active: sortKey == key }">
          {{ key | capitalize }}
          <span class="arrow" :class="sortOrders[key] > 0 ? 'asc' : 'dsc'">
          </span>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="entry in filteredData">
        <td v-for="key in columns">
          {{entry[key]}}
        </td>
      </tr>
    </tbody>
  </table>
</script>

<!-- demo root element -->
<div id="demo">
  <form id="search">
    Search <input name="query" v-model="searchQuery">
  </form>
  <demo-grid
    :data="gridData"
    :columns="gridColumns"
    :filter-key="searchQuery">
  </demo-grid>
</div>

Answer №1

If you want to properly interpret the content, you can utilize the v-html directive like this:

<td v-for="key in columns" v-html="entry[key]">

Note: Ensure to handle the quotation marks properly here:

{ name: 'Jet Li', power: 8000 ,report: '<a href="http://www.google.com">Google</a>'}

Vue.component('demo-grid', {
  template: `<table>
    <thead>
      <tr>
        <th v-for="key in columns"
          @click="sortBy(key)"
          :class="{ active: sortKey == key }">
          {{ key | capitalize }}
          <span class="arrow" :class="sortOrders[key] > 0 ? 'asc' : 'dsc'">
          </span>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="entry in filteredData">
        <td v-for="key in columns" v-html="entry[key]">
        
        </td>
      </tr>
    </tbody>
  </table>`,
  props: {
    data: Array,
    columns: Array,
    filterKey: String
  },
  data: function() {
    var sortOrders = {}
    this.columns.forEach(function(key) {
      sortOrders[key] = 1
    })
    return {
      sortKey: '',
      sortOrders: sortOrders
    }
  },
  computed: {
    filteredData: function() {
      var sortKey = this.sortKey
      var filterKey = this.filterKey && this.filterKey.toLowerCase()
      var order = this.sortOrders[sortKey] || 1
      var data = this.data
      if (filterKey) {
        data = data.filter(function(row) {
          return Object.keys(row).some(function(key) {
            return String(row[key]).toLowerCase().indexOf(filterKey) > -1
          })
        })
      }
      if (sortKey) {
        data = data.slice().sort(function(a, b) {
          a = a[sortKey]
          b = b[sortKey]
          return (a === b ? 0 : a > b ? 1 : -1) * order
        })
      }
      return data
    }
  },
  filters: {
    capitalize: function(str) {
      return str.charAt(0).toUpperCase() + str.slice(1)
    }
  },
  methods: {
    sortBy: function(key) {
      this.sortKey = key
      this.sortOrders[key] = this.sortOrders[key] * -1
    }
  }
})

// bootstrap the demo
var demo = new Vue({
  el: '#demo',
  data: {
    searchQuery: '',
    gridColumns: ['name', 'power', 'report'],
    gridData: [{
        name: 'Chuck s',
        power: Infinity
      },
      {
        name: 'Bruce Lee',
        power: 9000
      },
      {
        name: 'Jackie Chan',
        power: 7000
      },
      {
        name: 'Jet Li',
        power: 8000,
        report: '<a href="http://www.google.com">Google</a>'
      }
    ]
  }
})
<html>

<head>
  <meta name="description" content="Vue.delete">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.min.js"></script>
</head>

<body>
  <div id="demo">
    <!-- Grid template will be displayed here -->

    <!-- Root element for the demo -->
    <div id="demo">
      <form id="search">
        Search <input name="query" v-model="searchQuery">
      </form>
      <demo-grid :data="gridData" :columns="gridColumns" :filter-key="searchQuery">
      </demo-grid>
    </div>
  </div>
</body>

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

Error: Unable to access 'createInvite' property from undefined variable

Having trouble generating an invite to one of my guild's channels. Here is the code snippet I am using: const { Client } = require("discord.js"); const client = new Client({ intents: [] }); client.on("ready", async () => { ...

What is the method for accessing an app from a file other than server.js?

I am dealing with two different files: file1.js const app = express(); require('./file1/config/customConfigurations').customSettings() .then((settings) => { app.locals.customSettings = settings; console.log(app.locals.customSettings) ...

When attempting to access the length of a JSON array, it results in undefined

I recently received a JSON encoded array from an AJAX call that looks like this: {"country":{"0":"United States of America","United States of America":{"states":{"0":"Alaska","Alaska":{"cities":["Adak","Akiachak","Akiak","Akutan","Alakanuk"]}}}}} Below ...

Storing JSON data retrieved from a fetch API request in a JavaScript global variable - a beginner's guide

I have been experimenting with the fetch API and successfully managed to log the fetched data to the console using the then() method. However, I am struggling to store this data in a global variable for later use in vanilla javascript due to the nature of ...

Add content or HTML to a page without changing the structure of the document

UPDATE #2 I found the solution to my question through Google Support, feel free to read my answer below. UPDATE #1 This question leans more towards SEO rather than technical aspects. I will search for an answer elsewhere and share it here once I have th ...

Create a password variable while typing

Looking to avoid interference from browsers with autocomplete and password suggestions while maintaining the show/hide letters feature. The goal is to keep the password stored as a variable, regardless of whether the characters are shown or hidden. The is ...

Using Vuetify to create subtle fade in animation when scrolling

I'm attempting to create a fade-in effect while scrolling through the page for the first time. Even though I used <v-scroll-x-transition appear>, the desired effect doesn't seem to be working. Instead of fading in from the right as expecte ...

What is the best way to pass a JSON object from R to Plumber in a format that JavaScript can interpret as an array instead of

My goal is to receive a JSON raw response from R Plumber and then utilize it in Angular. However, I am encountering an issue where the JavaScript Framework is interpreting it as a string instead of recognizing it as JSON format. "[{\"id&bsol ...

Tips for Printing a div Element with Horizontal Scrollbars

My webpage has both vertical and horizontal scroll bars, but when I use window.print(), it only prints the visible content in the window. Is there a way to print the entire scrollable content within the window? ...

Issue with floating date and time not functioning properly in ICS file for Yahoo Calendar

I have set up a calendar event in Google, Apple, and Yahoo calendars for each individual customer. The event is scheduled based on the customer's address at a specific time, so there should be no need for timezone conversion. However, I encountered an ...

What is the method for creating a JavaScript array that closely resembles the provided example?

My task is to create an addRows method using specific data structure as shown below. data.addRows([ ['UK', 10700,100], ['USA', -15400,1] ]); However, the data I have available is in a different format. How can I transform ...

Tips on adjusting a standard CSS layout with JavaScript and jQuery to generate a unique ID for the updated style

My CSS contains IDs that look like this: <style> .HIDE-DISPLAY-k { background-color: orange; position: fixed; width: 100%; height: 100%; top: 10px; bottom: 0px; left: 10px; right: 0px; overflow: hidden; } #SHOW- ...

Throttle the RxJs interval based on the inner observables

Sorry if the way I am asking this question is not clear, I am having difficulty finding the right words to explain it. I am currently working on Selenium automation and here is how the process goes:- Go to a specific page Every 1 second, check if the pag ...

Tips for sending a form and showing results without the need to refresh the page

I am currently working on developing a basic calculator that takes a user input number and displays the calculated output without redirecting or reloading the page. However, since I have no experience with JavaScript (js) and Ajax, I am seeking assistance ...

Upon clicking the IconButton within the ImageListItemBar, reveal the image within a Material-UI Dialog

import * as React from 'react'; import Box from '@mui/material/Box'; import ImageList from '@mui/material/ImageList'; import ImageListItem from '@mui/material/ImageListItem'; import ImageListItemBar from '@mui/m ...

Leveraging the Railway Pathway from the Google Maps API

I need to customize my map to display only railway stations instead of the entire map. How can I achieve this? Below is the code I have attempted: <html> <head> <style type="text/css"> html { height: 100% } ...

Save the output of a knex query to a variable

I'm struggling to assign the result of a select query using Knexjs to a variable. Here is my code: function getAllCategories() { let categories; categories = database.from("categories").select("category").then(function (rows) { for (let row of ro ...

Having an issue with transmitting information to the database using ajax and Laravel

I am currently working on creating a drag and drop list that can be sorted. Each time an element is dropped into a new area, the order of the list should change accordingly. I am implementing this using AJAX and Laravel, but encountering an error when drop ...

Working with jQuery: Creating multiple lightboxes using the same jQuery code

Is there a way to create a universal lightbox with the same code for all lightbox functions on the page using JQuery? $(document).ready(function() { $('.lightbox').click(function() { $('.backdrop, .box').animat ...

Only allowing designated email addresses to authenticate using Gmail Oauth

Is there a way I can limit logins by doing the following? I'm facing an issue where the page keeps reloading constantly after logging in once. function onSignIn(googleUser) { var profile = googleUser.getBasicProfile(); console.log('Name: ...