Tips for modifying the content displayed on a v-list in Vue.js dynamically

I am looking to create a dynamic list that displays data based on the selected key. The list will contain multiple items with different keys, and I want the flexibility to choose which data to display without hardcoding the actual key value.

<template>
  <v-card
    class="mx-auto"
    max-width="500"
  >
    <v-list>
      <v-list-item-group v-model="model">
        <v-list-item
          v-for="(item, i) in items"
          :key="i"
        >
          <v-list-item-icon>
            <v-icon v-text="item.icon"></v-icon>
          </v-list-item-icon>
          <v-list-item-content>
            <v-list-item-title v-text="item.data_to_display"></v-list-item-title>
          </v-list-item-content>
        </v-list-item>
      </v-list-item-group>
    </v-list>
  </v-card>
</template>
<script>
  export default {
    data: () => ({
      data_to_display: 'name',   // or data_to_display: 'text'
      items: [
        {
          age: 34,
          name: 'abc',
          marks: null
        },
        {
          age: 12, 
          name: '',
          marks: 60
        },
        {
          age: '20',
          name: 'lmn',
          marks: 70
        },
      ],
      model: 1,
    }),
  }
</script>

This list contains various keys such as name, age, and marks. By selecting a key from the script, I can dynamically choose which data to display on the list.

Answer №1

If you follow @Sami's suggestion, you can utilize a key to display data and then use a computed property to filter out items with values:

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data() {
    return {
      data_to_display: 'name',  
      items: [{age: 34, name: 'abc', marks: null}, {age: 12, name: '', marks: 60}, {age: 20, name: 'lmn', marks: 70 },],
      model: 1,
    }
  },
  computed: {
    filteredItems() {
      return this.items.filter(i => i[this.data_to_display]  )
    }
  }
})
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b6d0d9d8c2f68098ce">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9debe8f8e9f4fbe4ddafb3e5">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet">
<div id="app">
  <v-app>
    <v-main>
      <v-container>
        <v-card
          class="mx-auto"
          max-width="500"
        >
          <v-list>
            <v-list-item-group v-model="model">
              <v-list-item
                v-for="(item, i) in filteredItems"
                :key="i"
              >
                <v-list-item-icon>
                  <v-icon v-text="item.icon"></v-icon>
                </v-list-item-icon>
                <v-list-item-content>
                  <v-list-item-title v-text="item[data_to_display]"></v-list-item-title>
                </v-list-item-content>
              </v-list-item>
            </v-list-item-group>
          </v-list>
        </v-card>
      </v-container>
    </v-main>
  </v-app>
</div>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80f6f5e5c0b2aef8">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1c6a697968757a655c2e3264">[email protected]</a>/dist/vuetify.js"></script>

Answer №2

By changing

v-text="item.data_to_display"
to
v-text="item[data_to_display]"
, you can resolve the issue at hand.

If a property name contains special characters, using brackets is necessary. Bracket notation comes in handy when dynamically searching for a property's values.

One of the objects has an empty value for the name property, which results in it being displayed as blank.

See the working demo below:

new Vue({
  el: "#app",
  vuetify: new Vuetify(),
  data: {
    data_to_display: 'name',
    model: 1,
    items: [{
      age: 34,
      name: 'abc',
      marks: null
    }, {
      age: 12, 
      name: '',
      marks: 60
    }, {
      age: '20',
      name: 'lmn',
      marks: 70
    }]
  }
})
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2c4c7d7f2809cca">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7c0a091908151a053c4e5204">[email protected]</a>/dist/vuetify.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f98f8c9c8d909f80b9cbd781">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet">
<div id="app">
  <v-app>
    <v-main>
      <v-container>
        <v-card
                class="mx-auto"
                max-width="500"
                >
          <v-list>
            <v-list-item-group v-model="model">
              <v-list-item
                           v-for="(item, i) in items"
                           :key="i"
                           >
                <v-list-item-icon>
                  <v-icon v-text="item.icon"></v-icon>
                </v-list-item-icon>
                <v-list-item-content>
                  <v-list-item-title v-text="item[data_to_display]"></v-list-item-title>
                </v-list-item-content>
              </v-list-item>
            </v-list-item-group>
          </v-list>
        </v-card>
      </v-container>
    </v-main>
  </v-app>
</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 is the best method for creating and passing a wrapped component to React Router?

I have multiple routes that I need to render different components for, and I want each component to be wrapped in a styled div. However, I'm looking for a way to write this code more efficiently. Is there a strategy to refactor this so that I can eas ...

Are strings in an array being truncated by Firebug console log?

I have a unique function for logging messages to the firebug console that I'd like to share: // Just having fun with names here function ninjaConsoleLog() { var slicer = Array.prototype.slice; var args = slicer.call(arguments); console.lo ...

Ensuring scope safety in jQuery AJAX requests

My intuition suggests that if I am on a laggy server and the user triggers two events quickly enough, the value of c in the success function will be based on the most recent event, potentially causing func1 to use the incorrect value. This is merely a hypo ...

switch the anchor tag value and send it along with the URL

I am trying to update the value of "trans" in the Ajax URL based on a toggle between on and off values. However, despite successfully toggling the text, the URL parameter does not change accordingly. Can anyone offer any assistance? I currently have to rel ...

Guide on selecting every input field located within a table

My form is embedded within a table <form id="form"> <input type="submit" value="send" class="btn btn-w-m btn-primary" style="float: left;">Add transaction</input> <table class="table table-strip ...

Linking information stored in an array to an object through the use of an intermediary object

How can we establish a connection between queued_Dr and upcoming_appointments using all_appointments? What would be the most effective solution for this issue? var queued_Dr = ["Dr.Salazar",["Dr.Connors","Dr.Johnson"],"D ...

How to Override Certificate Expiry in JavaScript

Is there a way to bypass security for an expired certificate when making an Https post request in Javascript? I have been successful in doing this with C# and Java, but unsure about how to proceed in JavaScript. function post() { var xmlhttp; xmlhtt ...

The nodejs server failed to respond to my request, displaying "undefined" instead

I have encountered some challenges while hosting my website on Firebase and Heroku Here are the issues I am facing: Initially, I am encountering CORS errors when trying to post data from a Firebase hosted URL to a server hosted on Heroku Even after re ...

Using AJAX, JQuery, and PHP to convert a given name to match the columns in a query, utilizing the data sent

One thing that I'm wondering about is how PHP handles my ajax requests. For example, consider the following code snippet: $("#addUser").on('click', '.btnAddSubmitFormModal', function() { $.post("add.php", { ...

Turn off Babel's strict mode when transpiling JavaScript files

Currently, I am facing an issue while trying to transpile a set of JavaScript files using Babel. Since Babel operates in strict mode by default, it triggers a syntax error whenever there is a conflict like the use of the delete keyword. The solution I am s ...

Unable to utilize jQuery within the NetBeans IDE

Whenever I try to include a jQuery file in Netbeans like this: <script type="text/javascript" src="js/jquery-1.3.2.js"> my code doesn't seem to work. However, when I use the following method: <script type="text/javascript" src="http://ajax ...

Displaying subtotal in a list using Vue.js and conditional rendering with v-if statement

Seeking guidance on calculating a total for a vue.js list that contains invoice items. To illustrate, let's consider a scenario where a table of invoice items is being rendered. Here is the code snippet: <table> <template v-for="(invoice_ite ...

Using React-Testing-Library to Jest TestBed Hook in TypeScript for Jest Testing

I'm currently facing a challenge while attempting to integrate the react-hooks library with Formik, specifically using useFormikContext<FormTypeFields>() in TypeScript within my project. I have certain fields where I want to test the automation ...

What is the best way to implement an AppBar that fades in and out when scrolling within a div?

I'm trying to implement a Scrollable AppBar that hides on scroll down and reappears when scrolling up. Check out this image for reference To achieve this functionality, I am following the guidelines provided by Material-UI documentation export defa ...

Do you know if there is a setting in prettier that allows line breaks to be preserved?

Encountering an issue with the prettier extension in VS Code, Whenever I enter the following code: const result = await pool .request() .query('select NumberPlate, ID, TimeStamp from RESULTS order by ID'); and save the file, it con ...

What could be causing my form not to Submit when attempting submission without utilizing the submit button?

Here is the code for my validation: $(function () { function validateForm() { // Code to validate form inputs } $('#myform').submit(validateForm); }); After this, I want to submit the form when a certain action occurs: < ...

Looking for a particular root node in a tree structure?

I am currently working on converting docx files to xml and using DOM to locate the parent node of a specific element. For instance <chapter> <title> <label>Chapter 1 </label> </title> ...

Summernote information embedded with HTML elements

I just started using the summernote text editor and I'm trying to figure out how to extract the content from the textarea without all the HTML tags. This is what I have in my code: <textarea class="summernote" id="summernote" ng-model="blog.c ...

Having trouble selecting an element by name that contains a specific string followed by [..] using jQuery

I have elements with names like kra[0][category], kra[1][category], and so on. However, I am facing difficulties in selecting these elements by name. Here is my jQuery code: $("[name=kra[0][category]]").prop("disabled", true); ...

The Microsoft.Azure.WebJobs.Script encountered an issue while attempting to cast an object of type 'System.String' to type 'Microsoft.AspNetCore.Http.HttpRequest' during the return process

I recently encountered an issue with my Azure Function written in JS that is triggered by the Service Bus and generates files to Blob Storage. When attempting to return an HTTP result, I received the following error message: System.Private.CoreLib: Except ...