The process on how to access dynamic object properties within a parent component while using v-for in a child component

I am working on a child component that utilizes v-for to loop through data. Below is the code for the child component:

<template>
    <div>
        <ul>
            <li v-for="item in listItems"
                :key=item.id>
                <span>{{item.name}} - {{item.color}}</span>
            </li>
        </ul>
    </div>
</template>

<script>
export default {
  props: {
    listItems: Array
  }
};
</script>

listItems stores an array of objects.

The challenge I'm facing is how to make the property names dynamic between the <span> tags from the parent component. Depending on the array of objects passed as listItems, there are times when I need the text within the <span> tags to vary based on the object properties in the array. For instance:

<span>{{item.id}} - {{item.location}}</span>

Answer №1

If you want to utilize scoped slots, you can do so like this:

   <li v-for="item in listItems"
                :key=item.id>
               <slot v-bind:item="item">
                 <span>{{item.name}} - {{item.color}}</span>
               </slot>
            </li>

Afterwards, you can use it in the following manner:

<child> 
  <template v-slot:default="{item}">
   <span>{{item.id}} - {{item.location}}</span>
  </template>
</child>

Alternatively, you can also use it like this:

<child> 
  <template v-slot:default="{item}">
   <p>{{item.location}}</p>
  </template>
</child>

Answer №2

When working with a limited number of options, consider implementing a sequence of

<span v-if="item.id">{{item.id}}</span> - <span v-if="item.foo">{{item.foo}}</span>
elements to display the desired information.

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

How to populate an ExtJS 3.4 combobox with local JSON data in a few simple steps

I am utilizing ExtJS 3.4 and in need of populating a combobox with specific data obtained from a previous XMLHttpRequest, stored in a variable as follows: my_variable = "[{"cod_domini":"1","nom_domini":"Sant Esteve de Palautordera"},{"cod_domini":"2","no ...

Deliver an assured result to a variable within the angular.extend() function

Can someone provide guidance on how to set myVar to a value returned from an asynchronous service method in the following example? angular.extend(this, { myVar: (function() { getVal(); })() }); function getVal() { var d = $q.defer(); ...

javascript exchange the content when clicking on a hyperlink

I'm encountering a bit of a challenge with this task... My javascript skills are a bit rusty, and I can't seem to pinpoint what's going wrong. My goal is to have a navbar that disappears when a user clicks on a small arrow, revealing a seco ...

Would it be expected for these two JQuery functions to exhibit identical behaviors?

If I have the following two JQuery functions - The first one is functional: $("#myLink_931").click(function () { $(".931").toggle(); }); The second one, however, does not work as expected: $("#myLink_931").click(function () { var class_name = $(thi ...

"Troubleshooting: The unique key prop is not functioning as expected with a

I am continuously receiving the warning message: Each child in a list should have a unique "key" prop. Even though I have assigned a key with an index number to my element, it does not appear in the HTML when inspecting via dev tools. The key values are a ...

Tips for adding multiple elements to the DOM at once

Is it possible to efficiently append elements to the DOM all at once? In the code snippet below, I am adding elements to a root element (tr_next) within a loop. $('.abc').each(function(){ //create element code here var tr_next = $("<tr> ...

What is the best way to add 1 to a number every second with javascript?

My code seems to be functioning correctly, but I'm having trouble setting the delay and stopping the increment after a certain interval. Can someone please assist me with this? Javascript: $(document).ready(function() { var number = parseInt($(& ...

What is the feature of a Vue.js component that removes other sibling markup?

While diving into the world of Vue, I encountered an interesting behavior that has left me wondering. I have my main markup set up and realized that a part of it could work as a separate component. However, when I tried adding this component to the contain ...

Traversing an array of objects in TypeScript and appending to a separate array if not already present

I have been given an array containing objects in the following format: export interface Part { workOrder?: string; task?: string; partNumber?: string; qty?: number; image?: string; name?: string; } My goal is to loop through each object in th ...

Drop down menus fail to appear after the screen has been resized

Creating responsive menus involves using ordered and unordered lists, along with CSS for styling. I have added a script to dynamically generate dropdown menus, but encountered an issue where nothing appears on the screen upon resizing - only the backgrou ...

Setting default values in select options in Vue3

Is there a way to set a default value for this template? I want the default value to be 'Please Select...', which is the first option in the list. <template #dropDownSelection="{ props }"> <td colspan="1"> ...

Utilizing React Router with Material-Table for Efficient Column Value Filtering

Is there a way to dynamically pass Route params into the filtering fields of a React table component? I am currently utilizing the material-table component and have a list of links structured like this: <ul> <li> <Link to="/Products/ ...

In ReactJS, ensure only a single div is active at any given moment

I'm working on a layout with three divs in each row, and there are multiple rows. Only one div can be selected at a time within a row, and selecting a new div will automatically unselect the previously selected one. Here is a simplified version of my ...

invoking an API within a map function and utilizing the response

vm.owners = parents.children.map(function(e) { getparentById(e.Id) .then(function(getresponse) { var parentLink = '<a href="/#/parent/onboard/' + e.Id + '" target="_blank">' + e.Number + "-&qu ...

Controlling LED lights using Johnny-Five and Arduino in NW.js

I have a setup with my board that includes two buttons (each with pull-up resistors) and two LEDs. My goal is to make each button activate its corresponding LED while deactivating the other one. Here's the code I'm using: var five = require(&ap ...

React and D3 Force Layout: uncharted territories for new links' positions

After carefully following the general update pattern for new React Props, I've noticed that D3 efficiently handles data calculation and rendering when receiving new props. This prevents React from having to render every tick. D3 functions seamlessly ...

Leveraging depends alongside max for jQuery validation

Trying to implement a conditional max value on a field using jQuery validation, but encountering issues. Even though I've utilized the depends function, it seems like the validate function is not functioning as expected. The code block appears correc ...

Errors in Chartist.js Data Types

I am currently using the Chartist library to monitor various metrics for a website, but I have encountered some challenges with the plotting process. The main errors that are appearing include: TypeError: a.series.map is not a function TypeError: d.normal ...

I am attempting to display text in the input box on the console, but unfortunately, I am not seeing any changes in the console when typing

I have this code, but I am not getting any output when I run it: import { restaurantList } from "../config"; import { RestrauntCard } from "./Restraunt"; const Body = () => { const searchText = "KFC"; return ( <& ...

Uncovering the Model within a controller in Ember JS

I am attempting to extract the original model object from a controller for the purpose of persistence (without utilizing ember-data). The straightforward approach would be: controller.get('content'); However, this method is not effective. The i ...