define a variable within a v-for loop

Example of Code

<div v-for="item in dataItems">
 <div v-if="enableEdit">
  <input type="text" v-model="name">
 </div>
 <div v-else>
   {{name}}
 </div>
<button @click="enableEdit = true">click</button>

This code snippet is currently not functioning properly due to the fact that enableEdit is not declared as a variable inside the script. Is it feasible to create a local variable within v-for?

Answer №1

To declare a variable inside of a template may seem impossible, but you can actually achieve the same outcome by following these steps.

Modify your template like this:

<div v-for="item in dataItems" :key="item.id">
  <div v-if="editedElementId !== item.id" @click="editItem(item.id)">
    {{item.name}}
  </div>
  <div v-else>
   <input type="text" placeholder="New name..." v-model="item.name" />
  </div>
</div>

Always remember to include :key when using v-for.

Next, insert editedElementId: null within the data section and create a new method called editItem:

methods: {
  editItem(id) {
    this.editedElementId = id
  }
}

Check out this link for a demo.

Answer №2

To handle cases where a value is undefined, you have the option to create a specific field name that pertains to the current iteration of the for loop:

<div v-for="(month, mi) in months" :key="mi">
    <div v-for="(day, di) in days" :key="di">
     ... <div v-if="generated_fields['month_' + mi + '_day_' + di]">
        ... <you_can_utilize_here> generated_fields['month_' + mi + '_day_' + di] ...
...
data:function(){
    return{
        ...
        generated_fields:{}//initially set as undefined, automatically populates when entered
        ...
}

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

Troubleshooting Issue: Failure of Ajax Script to Display Saved Data in Edit Function

Whenever I clicked on the Edit icon in the action column of my data tables, the saved data did not display as expected. I noticed that this issue was only occurring for file input types, while it worked properly for text input types. In the Blade file Ad ...

Does the language setting on a browser always stay consistent?

Using javascript, I am able to identify the language of my browser function detectLanguage(){ return navigator.language || navigator.userLanguage; } This code snippet returns 'en-EN' as the language. I'm curious if this i ...

Tips for properly utilizing GeolocationPosition in TypeScript

Our goal is to utilize the Geolocation API to access the user's location. This particular code snippet appears to be functioning well: if (navigator.geolocation) { navigator.geolocation.getCurrentPosition((position: GeolocationPosition) => conso ...

Incorporate AJAX functionality with a simple HTML button

Upon clicking the button, the AJAX call fails to execute. Below is the HTML code for the buttons: <td><button id=${data[i].id} name="update" type="button" value="${data[i].id}" class="btn btn-primary update" ...

A guide to categorizing and tallying JSON data based on multiple keys within the past 30 days using JavaScript/jQuery

I am facing an issue while trying to display a chart and extract specific data from an array. My goal is to generate a chart based on three columns in a JSON array: Source, Campaign, and Date. The process involves grouping the data, counting it, and then ...

Using jQuery in an external JavaScript file may encounter issues

As a newcomer to jQuery, I decided to try writing my jQuery code in an external js file rather than embedding it directly into the head of the HTML file. Unfortunately, this approach did not work as expected. Here is what my index.html looks like: < ...

Exploring the process of iterating through a JSON post response and displaying its contents within image divs

After receiving a JSON post response, I am looking to iterate over the data and display it in image divs. Can anyone provide guidance on how to achieve this using JavaScript? Thank you. Here is the JavaScript code that handles the JSON post response: cor ...

How can I modify a dynamically generated table to include rowspan and colspan attributes in the rows?

My table was automatically created using data from the database. var rows = ""; rows += "<tr class='row_primary'>"; rows += "<td>COL 1</td>"; rows += "<td>COL 2</td>"; rows += "<td> ...

Using TypeScript to define generic types for classes, method parameters, and method return types

I am facing an issue with this particular function function getCollection<T>(collectionType: T): Collection<T> { return new Collection<T>() } In the Collection class, I have the following code snippet export class Collection<T> { ...

Can you provide guidance on implementing StyledComponents within the app folder of Next.js version 13?

Quoting information from the Next.js documentation: Attention: CSS-in-JS libraries that rely on runtime JavaScript are currently not compatible with Server Components. The following libraries are supported in Client Components within the app directory: s ...

Adding a unique element to other elements in jQuery/Javascript can be achieved even when the existing elements only have classes assigned to them

One interesting feature of a Wordpress theme is the ability for site administrators to create forms with descriptions for each field. These descriptions share a common class, 'description,' and look like this: <div class="field-head"><l ...

How can I transmit information to the model without relying on query string parameters in Express?

Currently, I am working with two controllers - authController and onboardingController. The authController communicates with the onboardingController using the following line of code: res.redirect('/onboarding/info?profileId=' + profile.id + &ap ...

Show method created by function, substituting the former element on the display

showButtons(1) will show radio buttons for frame number 1, showButtons(400) will display radio buttons for frame number 400. The current code shows all radio buttons for every frame up to 400 HOWEVER, I am aiming for a single set of radio buttons to start ...

What are the steps to resolve routing issues within an Angular component integrated into an ASP.NET Core web application?

When it comes to routing in Angular, I have been following the Angular tutorial from documentation. My example application integrates Angular components with an ASP.NET Core 2.2 web app, and these components are displayed within .cshtml views. I use Angul ...

Fetching content and an image simultaneously via AJAX

My website features a photo gallery that I created using the code below: /*Begin Photo Gallery Code*/ var images = ['g1.jpg', 'g2.jpg', 'g3.jpg', 'g4.jpg']; function loadImage(src) { ...

What is the best way to implement Bootstrap 5 jQuery plugins in an ES6 project with Webpack?

Currently in the process of transitioning an ES6 project from Bootstrap 4 to Bootstrap 5, encountering the following error: Error: Uncaught TypeError: bootstrapElement.Tooltip is not a function According to the Migration Notes, Bootstrap 5 no longer inc ...

A guide on setting the array value on the user interface based on a key within the SectionList

My code is currently retrieving an array value and populating these values based on the key in a SectionList. The keys are displaying properly in the UI, but I am encountering some issues in my render item function, particularly in the second section. Esse ...

Is it possible that React useState is not allowing a default value to be set in this case?

In my chart component, I have the functionality to show/hide specific lines. To keep track of active lines, I maintain an array called activeKeys in a state. Initially, I populate this array by calling a function named getKeys, which takes an array of data ...

Nuxt.js Button Dropdown Widget

Currently, I am in the process of creating a button similar to a dropdown. This particular button is meant for printing and downloading documents. Here is the code I have implemented: <template> <v-menu transition="s ...

Unable to set initial values for Select Option in Redux-Form

I have implemented an update form using redux-form, where the form value is initialized using initialValues. For example: <DataEdit initialValues={ Data }/> The form in the DataEdit page looks like this: <Field name="Data.taxTitle" comp ...