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

What is the best way to incorporate a function within a $.click (jquery) event that utilizes an id directly from the clicked element?

It seems that my title may not be very clear, but I have a jQuery code snippet that is causing some issues. The problem stems from the fact that when I click on an image with the class 'slideimg', I expect a function named slideDo to be executed, ...

Achieve resumable uploads effortlessly with google-cloud-node

While this code works well for regular uploads, I am curious about how the resumable upload feature functions when a user loses connection during a large upload. Does simply setting 'resumable' to true in the writeStream options make it work effe ...

Searching across multiple attributes in Jquery UI Autocomplete: A comprehensive guide

My data is stored in an array of objects with a structure similar to this: $scope.usersList = [{ "name": "John", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f09a9f989eb088898ade939f9d">[email protected ...

I am having trouble viewing the input value on my Angular5 form

Here is the HTML code snippet that I've written: <input type="text" name="fechainscripcion" #fechainscripcion="ngModel" [(ngModel)]="alumno.fechainscripcion" value="{{today | date:'dd/MM/yyyy'}}" class="form-control" /> This is a seg ...

Unlocking the secret to accessing keys from an unidentified data type in TypeScript

The code snippet above will not compile due to an error with the email protection link. const foo: unknown = {bar: 'baz'} if (foo && typeof foo === 'object' && 'bar' in foo) { console.log(foo.bar) } An erro ...

Having issues with @ts-ignore in Typescript on a let variable that is not reassigned?

JOURNEY TO THE PROBLEM My current task involves destructuring a response obtained from an Apollo useLazyQuery, with the intention to modify one variable. In a non-Typescript environment, achieving this would be straightforward with just two lines of code: ...

Utilizing Vue 3 to transform an item within a list by referencing its index

Storing the element's index in a global variable is causing issues when trying to individually edit each of them. Adding multiple elements with similar properties but being unable to edit them separately due to alterations affecting the rest is a chal ...

Develop a voice recording feature using ReactJS

In my quest to enhance a chat application with voice recording functionality, I came across the react-mic package. It worked smoothly and provided me with the data needed at the end of the recording session. (link: https://i.stack.imgur.com/nhNCq.png) Now ...

Creating an associative array in javascript: A step-by-step guide

I require an array to be structured in the following manner: {"3": {"label":"All i want for christmas", "song":"Alliw_1405399165.mp3", "name":"All i want for christmas"}, "4": {"label":"Call your girlfriend robyn clip", "song":"Gang ...

Progressive Web App with Vue.js and WordPress Rest API integration

When creating an ecommerce website using Wordpress, I utilized Python for scraping data from other websites to compare prices and bulk upload products through a CSV file. My next goal is to learn Vue and transform the website into a PWA as it will be esse ...

Error: An unexpected TypeError occurred while attempting to fetch an array or collection from MongoDB Atlas

As a beginner in the world of Express and Mongoose, I am currently working on retrieving an object from MongoDB Atlas using Mongoose.Model for educational purposes. In CoursesModel.js, I have defined the schema for my collections and attempted to fetch it ...

Exploring the possibilities of maximizing, minimizing, resizing, and creating a responsive design in dialog boxes using jQuery UI JavaScript and

I'm trying to create a dialog with maximize, resize, and minimize buttons like those found in Windows OS. I want the dialog to be responsive and draggable as well. I've been using jQuery, jQuery UI, and extended dialog frameworks, but I haven&apo ...

Optimizing the display of multiple list items using Javascript for two separate UL elements on a single webpage

How can I display a maximum of 5 list items in two separate UL elements on the same page and hide the rest? Users should be able to see more items by clicking a dynamic "See more" element created by JavaScript. Below are the UL elements I want to work wit ...

The error alert must be displayed directly beneath the specific box

When error messages occur in this code, they are displayed through an alert box. However, I would prefer to have the error message appear below the specific text box instead. This means that when I click on the submit button and a field is left empty, the ...

Applying onclick css changes to a specific duplicate div among several others?

Recently, I encountered a situation where I have multiple identical divs on a page. <div class="class" ng-click="example()"></div> With the use of Angular 1.6.4 and jQuery, these divs are styled with background color and border color. Now, w ...

Error handling: Encountered unexpected issues while parsing templates in Angular 2

I'm a beginner with Angular 2 and I'm attempting to create a simple module, but encountering an error. app.component.html import { Component } from '@angular/core'; import { Timer } from '../app/modules/timer'; @Component({ ...

showing information on webpage 2 received via query parameters from webpage 1

Hello, I am trying to input text into a textarea and then send the data through a query string to another webpage. My goal is to display the data on the second webpage. I have written the following code, but it doesn't seem to be working. I've ch ...

Purging the JavaScript output

Currently, I am calling an API and receiving a list of results. These results are then processed into an object for iteration and display. Below is the function responsible for this process: var getAvailability = () => { if (chosenData.hot ...

The 3-way data binding in angularFire does not update a function

My issue involves a firebaseObject (MyFirebaseService.getCurrentUser()) being bound to $scope.user. Once successfully bound, I iterate through the object to check if it contains an "associatedCourseId" equal to a specific value ($stateParams.id). If it doe ...

Can anyone help with displaying a PNG image in Vue/Node/Express? I am struggling to show the image that I sent from a Node.js server to a Vue app client

In my Node/Express application, I've set up a route like this: app.get('/get-image', function(req, res) { ... res.sendFile(path.join(__dirname, '..', account.profileImg)); }) Now in my client-side Vue app, I'm tryi ...