What is the best way to showcase a single item from an array in Vue.JS?

Suppose I have a list of items in Vue.JS

data () {
return{
  items: [
    {
      itemID: 5,
      itemText: 'foo'
    },
    {
      itemID: 3,
      itemText: 'bar'
    }
  ]
}
}

Now, if I want to show the item with the itemID of 3 in a previously created element

<Item 
  v-for="item in items"
  :key="item.itemID"
  :item="item"
/>

I want to display all the content from that item (the ID and the text)

Item component :

<template>
    <div class="item">
        <div class="item-id">
            <h1>ITEM ID: {{ item.itemID }}</h1>
        </div>
        <div class="item-task">
            <h2>{{ item.itemText}}</h2>
        </div>
    </div>
</template>
 
<script>
 
export default {
  name: 'Item',
  props: ['item']
}
</script>

Answer №1

Avoid using both v-if and v-for within the same element. Instead, it is recommended to utilize a computed property that specifically returns the desired example:

data () {
return{
  examples: [
    {
      exampleID: 8,
      exampleText: 'baz'
    },
    {
      exampleID: 2,
      exampleText: 'qux'
    }
  ]
}
},
computed:{
    selectedExample(){
       return this.examples.find(ex=>ex.exampleID===2)
    }
}

Subsequently, you can render it as follows:

  <Component   :example="selectedExample"/>

Answer №2

One alternative method that avoids using v-for is

data () {
return{
  samples: [
    {
      sampleID: 7,
      sampleText: 'baz'
    },
    {
      sampleID: 9,
      sampleText: 'qux'
    }
  ],
  identifier: 9
}
},
computed:{
    findSample(){
       return id => this.samples.find(s=>s.sampleID===id)
    }
}

The implementation will look something like

<Component :sampleData="findSample(identifier)"/>

This approach eliminates the need to explicitly specify the value as 9 in the computed property.

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

Tips for retrieving JSON data using ajax with jPut

Recently, I stumbled upon a handy jQuery plugin called Jput that allows for easy appending of JSON data to HTML content. You can check it out here. However, I am curious about the process of sending and retrieving JSON data via AJAX. Any insights or guida ...

Steps to dynamically set the value of an input type="time" using JavaScript

Despite the repetitive nature of these questions, I have yet to find a solution to my specific query. Any help would be greatly appreciated. Thank you in advance. The HTML code is as follows: var start="10:30 PM"; $scope.edit={} frtime=start.split("PM ...

IE8 triggers automatic download upon receiving JSON response using jQuery

Can you help me make IE8 compatible with this code using jQuery to handle an ajax request that returns data as JSON? $.ajax({ url: formAction, type: 'post', dataType: 'json', data: form, success: ...

Fastblox - utilizing javascript SDK for group chatting

I've been facing issues setting up a group chat using QB Javascript SDK. There are a few problems I am encountering: Firstly, I consistently receive a "room is locked" message. Here's the link to the screenshot: https://i.sstatic.net/auR21.png. ...

Ensure to verify the `childProperty` of `property` within the `req.checkBody

When working with Node.js, a common practice is to use code like the following: req.checkBody('name', 'Group name is required.').notEmpty(); In a similar fashion, I have implemented something along these lines: req.checkBody('pa ...

I am looking to transform CSV data into XLSX file format, upload it to AWS, and obtain the corresponding URL

I am currently in the process of converting a JSON file to CSV. My next step is to convert this CSV file to XLSX data and upload it to AWS to retrieve the link. Convert CSV to XLSX const xlsxFilePath = 'path/to/transaction_data.xlsx'; await csvto ...

Pass the PHP data back to my existing webpage for JavaScript to retrieve

I recently set up a form on my WordPress website for users to submit data. Once the form is submitted, I use AJAX to create a new post without having to reload the page. I now need to figure out how to pass the post ID, a simple integer, back to the page s ...

Adjust the div class to align with its content

I am looking to modify the code in order to copy the text of a div to its own class. Currently, the code provided copies text from all sibling div elements, but I specifically want each individual div's text to be its own class. For example, with the ...

Nuxt js - Components are replicated on SSR pages

I have created a static page containing various components. When I navigate to this page from another page, everything displays correctly. However, when I directly land on the page, some components are duplicated and rendered again after the footer. Upon i ...

What is the best way to enhance this current array with additional submenus?

Code for current array: function fetch_menu($menu = array(), $ulclass = '', $is_main_menu = false) { global $menu_selected; $output = ''; if (empty($menu)) { return $output; } $output .= '<ul' ...

Tips for getting a sticky table header and including a limited number of columns, each with checkboxes or input fields

Encountering issues while trying to implement functionality with a jQuery library. One specific problem is the inability to interact with checkboxes on sticky columns, as well as difficulties clicking and typing in text fields. I am utilizing the jQuery S ...

What is the best way to prevent the body from scrolling when scrolling on a fixed div without making the body's scroll bar disappear?

Is there a way to prevent the body from scrolling while I scroll on a fixed div? I attempted using overflow:hidden for the body, which stops scrolling but causes the page to shake when the scroll bar disappears. Is there a solution that allows me to keep ...

A viewless Angular 2 component

Is it feasible to utilize Angular 2 without the need for a template or an @View? I am exploring alternative methods akin to the example shown below: Angular 1 index.html <div ng-controller="appcontroller"> <div ng-class="{active: isActive()}"& ...

Developing user registration and authentication using Backbone.js in conjunction with Django Rest Framework

In the process of developing my app, I am utilizing backbone.js for the frontend and django-rest-framework for the backend. My goal is to enable user registration, login, logout functionality, and be able to verify whether a user is logged in using backbon ...

How can AngularJS ng-repeat be used to extract HTML elements?

I need help parsing HTML that is received from the server as a string. Here is an example of what I receive: <img src="http://gravatar.com/avatar/9a52267d32ad2aaa4a8c2c45b83396e5?d=mm&amp;s=&amp;r=G" class=" user-1-avatar avatar- photo" width=" ...

Updating the URL in React and Redux

I am currently working on developing an application using React and Redux (DVA) with Ant.Design as the main framework. I am facing an issue where I need to change the URL when a user clicks on a button, and connect that URL change to a specific action so t ...

Using Vue.js for redirecting with a post method

Is there a way to redirect from Vue.js to a Laravel controller using the POST method without using AJAX? I would like to be able to use var_dump or dd inside the controller. //Vue.js axios.post('/add-hotel-listing', this.finish).then((respons ...

Using Jquery to send json data to a webserver via Ajax (API)

Currently, I am attempting to use AJAX to post data to a JSON file (API) on a server. As part of this process, I have implemented dragging functionality for two Kineticjs shapes on the stage. Upon stopping the drag action, my goal is to save the updated x ...

I am searching for a straightforward Rails sample that incorporates Ajax

Currently, I am on a quest to find a solid demonstration of how AJAX and JSON interact with Rails. I have a Rails application that relies on standard forms and I am looking to enhance it with some ajax functionality. Unfortunately, I haven't come acro ...

Utilizing Laravel 6 alongside Vue.js and webpack in place of the traditional Vue implementation

Starting a new Laravel project, I used the composer create-project --prefer-dist laravel/laravel FullStack command to set it up. Next, I included Vue.js with the composer require laravel/ui command, followed by running npm install and npm run dev. Expecti ...