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

Uh-oh! An unexpected type error occurred. It seems that the property 'paginator' cannot be set

I am developing a responsive table using Angular Material. To guide me, I found this helpful example here. Here is the progress I have made so far: HTML <mat-form-field> <input matInput (keyup)="applyFilter($event.target.value)" placeholder ...

Tackling the sticky header problem with in-browser anchoring and CSS dynamic height restrictions

I am experimenting with a unique combination of a Pure CSS in-page anchoring solution using scroll-behavior: smooth and scroll-margin-top settings, along with a sticky header for in-page navigation. By utilizing IntersectionObserver, I can identify when t ...

Ubuntu is experiencing a DNS problem. While the URL request works perfectly on MacOSX, it is unsuccessful on Ubuntu

A custom nodeJS script has been developed to utilize the require('request').post() method. The script executes successfully on MacOSX (Travis), however encounters issues on Ubuntu (Travis). To troubleshoot, experimentation with NodeJS 'https ...

Dynamic styling based on conditions in Next.js

After a lengthy hiatus, I'm diving back in and feeling somewhat disconnected. In short, I have encountered a minor challenge. I successfully created a navigation menu pop-out that toggles classname based on the isActive condition in React. However, I& ...

Outputting main value using Vue.js loop

Below is an array example: data() { return { shoppingItems: [ {name: 'apple', price: '10'}, {name: 'orange', price: '12'} ] } } I am attempting to loop through it as shown below: <ul> ...

Error encountered in NEXT JS: Unable to parse URL from /api/projects or Error message: Failed to connect to 127.0.0.1:3000

Currently utilizing: export const getStaticProps = async () => { export const getStaticPaths = async () => { and accessing my API (pages/api/projects/) created with Next.js on my local host const res = await fetch("http://localhost:3000/api/ ...

Photoswipe using identical source code, yet the output is malfunctioning

Having an issue with my code that refreshes the content of a ul element. Initially, it works fine by directly loading the ul content, but I am constantly creating new content every 10 seconds to provide users with fresh updates. Even though the source co ...

Embed an external website within a div element

Is there a way to embed an entire external website onto another site, without scroll bars or borders? I attempted this method but the entire page did not load, and there were still scroll bars and borders present. <!DOCTYPE HTML> <html> <b ...

You can disregard the first option in a multiple select box using jQuery

Imagine having multiple select boxes with the same options that are mutually exclusive. For instance, if Select Box A and Select Box B both have Option 1, Option 2, and Option 3, selecting Option 1 for Select Box A should make it unavailable in Select Box ...

What are the steps for defining the maximum and minimum values in AngularJS?

I'm working with the following HTML markup: <div class="input-group-icon">Max <span class="error">*</span> <div class="input-group"> <input style="border-right:none;" name="available_funds_max" ng-model="attributes.avai ...

What's the issue with my jQuery AJAX script?

I am experiencing an issue with my ajax pages using jQuery to retrieve content. Only one page seems to be working properly, even though I have multiple pages set up. How can I resolve this problem? $(document).ready(function() { $('.lazy_content& ...

Use .load() to set an image as background in the div

There is a block of code that is supposed to display images in a div with the class "img", but it isn't functioning correctly. Can you provide some guidance on how to fix this issue? <div class="other"><a href="/index1.html">Link1</a&g ...

What is the best way to retrieve a variable from MySQL in a Node.js environment?

var result; function getName(id) { //Retrieve name from database connection.query(`SELECT name FROM users WHERE id = "${id}"`, function (err, rows, fields) { if (err) console.log(err); result = rows[0].name; }); console.lo ...

Unit testing with Jest involves creating mock implementations of IF conditions within functions to ensure complete code coverage

Currently, I am working with an API script stored in a file. const ApiCall = { fetchData: async (url) => { const result = await fetch(url); if (!result.ok) { const body = await result.text(); // uncovered line throw new Error(`Err ...

How can I incorporate the `name` parameter into a `redirect` URL using vue-router?

Below is the setup of my router in the Vue project import { createRouter, createWebHistory } from "vue-router"; const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: [ { path: "/", ...

Conceal elements with a single click of a button

How can I use jQuery to hide all li elements with an aria-label containing the word COMPANY when the Search from documents button is clicked? Here is the HTML code: <ul class="ui-autocomplete ui-front ui-menu ui-widget ui-widget-content" id="ui-id-1" t ...

Add the content script to a webpage just one time

I am looking to inject a content script on context menu click in an extension manifest version 3. I need a way to determine if the script is already injected or not. If it hasn't been injected yet, I want to inject the content script. This condition m ...

The timing calculations in Vue.js do not align with the standard JavaScript version

I am currently working on developing a 'beats per minute' (BPM) calculator, which is similar to the one available here. However, I have noticed that when using the BPM calculator from that link for testing on a particular song, it quickly approxi ...

Difficulty accessing Vue data passed from parent to child component

In my app.vue file, I have the parent code for a Vue app. <template> <div id="app" class="small-container"> <h1>Employees</h1> <employee-form @add:employee="addNewEmployee" /> <employee-table :employees="empl ...

straightforward multiple second timer

I have multiple <span class="timer">342</span> elements with different values (in seconds). I am trying to create a countdown timer for all of them by using the following code: $('.timer').ready(function() { ...