Reputation: 2425
Code snippet
<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 is not working because enableEdit
is not declared as variable inside script.
Is it possible to create a local variable inside v-for?
Upvotes: 0
Views: 1821
Reputation: 12564
Handling the undefined, you can generate a field name that is specific for the actual 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]">
... <here_you_can_use> generated_fields['month_' + mi + '_day_' + di] ...
...
data:function(){
return{
...
generated_fields:{}//for fields starts undefined, autofills when written
...
}
Upvotes: 0
Reputation: 3653
Creating a variable inside of template is impossible as far as I know, but you can achieve the same effect by doing the following.
Edit your template:
<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>
Remember to always use :key
with v-for
.
Then add editedElementId: null
inside of data
and a new method editItem
:
methods: {
editItem(id) {
this.editedElementId = id
}
}
http://jsfiddle.net/eywraw8t/317760/
Upvotes: 1