Reputation: 573
Let's say we have rendered the following template which represents a book
:
<div class="book">
<h1 class="book__title" ref="title">{{book.title}}</h1>
<p class="book__description">{{book.description}}</p>
<button @click="activateEditMode">Edit Book</button>
</div>
I would like to allow my users to quickly edit this book. When users click the Edit Book
button, they should be able to edit inline. It is as if the .book
card is replaced by a form. It is similar to how Facebook allow its users to edit comments inline.
I have tried replacing the <h1>
and <p>
elements with a corresponding <input>
and <textarea>
elements programatically in the activateEditMode()
method:
activateEditMode() {
let bookTitle = this.$refs.title;
let bookTitleInput = document.createElement('input');
// but how do we programatically attach the v-model="book.title"
// binding to our newly created input element here?
bookTitleInput.value = this.book.title;
}
How would we attach our v-model binding to our newly created input element using JavaScript?
Is this the best approach to do this?
Upvotes: 1
Views: 3314
Reputation: 39456
As DMan noted, what you want could be easily achieved like so:
<template v-if="!editing">
<h1>{{ book.title }}</h1>
<p>{{ book.description }}</p>
<button @click="editing = true">Edit</button>
</template>
<template v-else>
<input v-model="book.title">
<input v-model="book.description">
<button @click="editing = false">Done</button>
</template>
Upvotes: 3