first I will explain my problem and what I'm doing. I'm coding a component that represents a single row within a table. That component at first shows information about a category (Its name, description and id). I've an Edit button where I can edit the name and the description of each category. Looks like this:
When I click the edit button I replace the data with inputs (only in Name and Description), so I'm able to change the values I then send the information to the server.
So, what's the problem? The problem is that when I press the edit button, then I change the input value (It's bound with v-model) and then I press the Edit button again (so I don't want to change the data) the data actually remains as the input was and I don't want that. I just want the initial value.
Well, I've solved that by using :value instead of v-model (maybe there is another way?).
The thing is that when I save the changes and then I check if the input is correct It re-renders the DOM (when I show an error message) and so the value that has initially the input and I don't want that. Here is the component's code:
<template>
<tr>
<th>
{{idCategory}}
</th>
<td>
<p v-if="isEditingCategory === false">
{{category.name}}
</p>
<form class="field" v-show="isEditingCategory">
<div class="control">
<input class="input"
type="text"
:value="category.name"
ref="categoryNameInput"
style="width: auto;">
</div>
<p class="help is-danger" v-show="showHelpMessage">al menos 3 caracteres.</p>
</form>
</td>
<td>
<!-- TODO. hacer un pipe para que muestre solo los primeros 10 caracteres. -->
<p v-if="isEditingCategory === false">
{{ category.description }}
</p>
<form class="field" v-if="isEditingCategory">
<div class="control">
<input class="input" type="text" :value="category.description" ref="descriptionInput" style="width: auto;">
</div>
</form>
</td>
<td>
<!-- Buttons... -->
<button class="button is-info is-outlined" @click="onEditCategory">
<span class="icon">
<i class="fas fa-edit"></i>
</span>
</button>
<button class="button is-success"
@click="onSaveCategory"
v-if="isEditingCategory">
<span class="icon">
<i class="far fa-save"></i>
</span>
</button>
</td>
</tr>
</template>
export default {
data() {
return {
isEditingCategory: false,
isPostingChanges: false,
category: {
id: this.idCategory,
name: this.categoryName,
description: this.categoryDescription,
index: this.arrayIndex
},
showHelpMessage: false
}
},
methods: {
onSaveCategory() {
this.showHelpMessage = false;
const MIN_CHAR = 3;
const categoryNameValue = this.$refs.categoryNameInput.value;
const descriptionValue = this.$refs.descriptionInput.value;
if (categoryNameValue.length >= MIN_CHAR) {
console.log(categoryNameValue)
} else {
this.showHelpMessage = true;
}
},
onEditCategory() {
this.isEditingCategory = !this.isEditingCategory;
}
},
props: ['idCategory', 'categoryName', 'categoryDescription', 'arrayIndex']
}