Setting up a variable within a v-for iteration in Vue JS

I'm currently facing a challenge in finding a solution to what appears to be a simple problem.

Within a template, I am using a v-for loop to generate some content. In this content, I need to execute a function to check if the contentID matches an ID from a separate list. If there is a match, I need to display that data within my loop. However, the current method involves running the function multiple times, as shown below:

methods: {
findClientName (clientId) {
  for (let name of this.clientList) {
    if (name.id == clientId) {
      return {
        name
      }
    }
  }
}

<v-card-text>
    {{ findClientName(item.client_id).name.f_name }}
    {{ findClientName(item.client_id).name.l_name }}
</v-card-text>

It feels inefficient to call the method repeatedly on each data point. Is there a way to store the result in a local variable within the template, like this:

{ clientData = findClientName(item.client_id) }
{{ clientData.f_name }}
{{ clientData.l_name }}

What am I overlooking or not considering?

Answer №1

It is advisable to utilize a computed property in this scenario and iterate through that property using v-for. Below is an example provided to replicate your situation:

new Vue({
  el: '#app',
  data: {
    a: ["aaa", "bbb", "ccc", "ddd", "eee", "fff"],
    b: ["bbb", "sss", "ccc", "eee"]
  },
  computed: {
    isInA() {
      return this.b.filter((item) => {
        return this.a.includes(item)
      })
    }
  }

})
<!DOCTYPE html>
<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="app">
    <div v-for="item in isInA">
      {{item}}
    </div>
  </div>

If your arrays consist of objects like your case, you will need something like this:

computed:
 cpt_clients(){
return this.clientList.filter((cl)=>{
                          return this.otherList.findIndex(item=>{return item.id==cl.id;})!==-1;
                        });
         }
       }

and in your template, use the following:

  <v-card-text v-for="cl in cpt_clients" >
       {{cl.name}}
        {{cl.id}}
   </v-card-text>

Answer №2

If you find yourself needing data from another list, you may need to perform a lookup. One approach could be to normalize the client list beforehand and then utilize it in the template loop. Consider the following example:

data () {
  return {
    mapped: [],
    clientList: [...]
  }
},
mounted () {
  this.mapped = this.clientList.map(({ id, f_name, l_name }) => {
    return { [id]: { f_name, l_name } }
  })
}

With this setup, your template would look like this:

<template>
 ...
    <v-card-text v-if="mapped.hasOwnProperty(item.client_id)">
      {{ mapped[item.client_id].f_name }}
      {{ mapped[item.client_id].l_name }}
    </v-card-text>
 ...
</template>

Answer №3

I have discovered a clever workaround to address the absence of local variables in this situation. By encapsulating the value within a single-element array, I can take advantage of VUE's built-in support for array iteration:

<template v-for="local_variable in [object.longComputationValueProducer().evenMoreCPUWork()]">
    <!-- This block will be run exactly once -->
    <div>{{ local_variable.read }}</div>
    <div>{{ local_variable.read_without_recompute }}</div>
    <div>{{ local_variable.read_again_without_recompute }}</div>
</template>

Answer №4

Personally, I believe computed is superior to method because it relies on your localId for functionality.

computed: {
   getClientsById (clientId) {
     return this.currentClientList.filter((ccl) => { return this.currentClientList.id === localId });
   }
} 


<v-card-text v-for="item in getClientById">
    {{ item.name }}
</v-card-text>


// Another approach without the use of methods and computed

<v-card-text v-for="item in currentClientList" v-if=item.id === localId>
    {{ item.name }}
</v-card-text>

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

Node unable to interpret accented characters from CSV file input

Currently, I am utilizing npm fast-csv as my CSV reader/writer tool. It offers a simple and straightforward way to handle CSV files. My goal is to use this tool along with iconv to deal with "accented" characters and non-ASCII characters by converting them ...

Unusual Type Inference in Typescript {} when Evaluating Null or Undefined

Upon upgrading from typescript 4.9.3 to 5.0.2, we encountered an error when asserting types. Can someone explain why the function "wontWorking" is not functioning correctly? I expected this function to infer v as Record<string, any>, but instead it ...

Error: null value cannot be scrolled into view - testing with react, jest, and enzyme

Utilizing react version 16.3.1, jest version 16.3.1, and enzyme version 3.3.0. Inside my React Class component, I have implemented a react ref to ensure that upon mounting the component, the browser scrolls back to the top of the page. class PageView ext ...

Sorting Columns in JQuery Datatables

Encountering an issue with JQuery DataTables (datatables.net) where it takes 2 clicks to sort the columns when there are only 2 rows in the table. The first column sorts on the first click, but subsequent columns require multiple clicks. Despite testing th ...

The Material UI date range picker fails to close once a selection has been made

I'm currently using the Material UI date range picker, but I've encountered an issue. After selecting the dates, the date picker does not close automatically. How can I make it close once the dates are selected? I couldn't find any specific ...

Challenges with HTML and JavaScript

Struggling to get this code to work properly with Node.js. const express = require('express') const app = express() app.use(express.static('public')) //includes content of public folder app.get('/', function (req, res){ ...

Creating a simulated RESTful backend using Sinon.js for an Angular.js project

In the process of developing my Angular.js application, I am incorporating RESTful services that utilize the $resource service. While this app will eventually connect to a Java Spring application, I am currently focusing on creating an isolated mock server ...

Incorporating Chakra UI, what is the best way to display a modal box upon page load?

Is there a way to display a modal box when the page loads in Chakra UI? I have been searching through Chakra's documentation but couldn't find any information on this. import { useDisclosure, Modal, ModalOverlay, ModalContent, ...

Typing in Text within Kendo Textbox using Protractor

I'm encountering an issue with Protractor while trying to input text into a Kendo TextBox. The error message I receive is "ElementNotVisibleError: element not visible". Interestingly, when the text box is clicked on, the "style="display: none;" change ...

What is the maximum character limit for the JQuery validation plugin?

Currently, I am utilizing the JQuery validation plugin in my project. My goal is to set a maxlength for one of the fields. Here's an example of how it can be done by defining rules externally: rules: { Message: { required: false, maxLe ...

Scrolling to the complete height of a div using scrollTop

Experience an automated scroll to the bottom of the div, followed by a smooth upward motion over 5 seconds, all while looping seamlessly. A small issue arises where the code only recognizes the standard height set for the div, not its actual scrollable he ...

What is the process for a server to transmit a JWT token to the browser?

Here is an example response sent to the browser: HTTP / 1.1 200 OK Content - Type: application / json Cache - Control : no - store Pragma : no - cache { "access_token":"MTQ0NjJkZmQ5OTM2NDE1Z ...

Unable to utilize material tabs in this situation

Discovering the material tabs feature at https://material.angular.io/components/tabs/api#MatTab got me excited to implement it in my project. After adding the suggested import, I encountered an issue where I couldn't find the module "@angular/materia ...

Error: The function you are trying to reference is undefined

I am facing an issue where I am receiving a "ReferenceError: doNotification is not defined" message when attempting to display a pop-up notification upon successful promise. Oddly enough, triggering doNotification on button click within my HTML works wit ...

Utilize mapping function to merge arrays

Currently facing an issue with no clear solution in sight. When making API calls via a map, I am able to successfully log all results individually. However, my challenge lies in combining these results into a single array. var alpha = ['a', &apo ...

I am unable to modify the local JSON file during runtime

Is there a way to avoid bundling a local JSON file in my app? I am able to import and use it during development, but once the app is built, the file gets bundled and I can no longer access or modify it. I need the JSON file to remain separate so that I ca ...

Instructions on creating an individual DropdownIndicator component with React-select for the purpose of reusability in different sections of the project

The code below functions properly when the DropdownIndicator component is kept in the same file. However, I am interested in separating DropdownIndicator into its own file so that it can be reused. This way, it can be used as a separate component and incl ...

Modify all the content within the DIV using Regex, while keeping the HTML tags intact

I am attempting to replace all the text inside a DIV, including within its children, without modifying any HTML tags. Specifically, I want to switch all instances of 'Hello' to 'Hi'. Thank you for your help. var changes = $('div ...

Tips on setting and utilizing custom environment variables in a Vue Electron application

What is the best way to integrate custom environment variables into my Electron application? I need to securely store API keys and other sensitive information without hardcoding them directly into the code. My app is built with Vue and Electron. To tackle ...

Using JavaScript to Establish Default Homepage in FireFox and Internet Explorer

How can I set a web address as the default homepage for a client? Specifically looking for solutions for (pageload) on IE8 and Firefox 3 (or newer versions). Thank you in advance for your help. Best regards ...