Issue
I have post.title
and post.body
in value, and I need that after changing the values in the text inputs, it is saved in data so that I can use these new values later for the user to write (PUT
request) on the API. How can I achieve this?
Here's my code -
<template>
<div id="app">
<input type="text" v-model="createTitle" />
<input type="text" v-model="createBody" />
<button @click="addPost()">AddPost</button>
<ul>
<li v-for="(post, index) of posts">
<p>{{ post.title }}</p>
<p>{{ post.body }}</p>
<button @click="deleteData(index, post.id)">Delete</button>
<button @click="visiblePostID = post.id">
Изменить
</button>
<transition v-if="visiblePostID === post.id">
<p><input :value="post.title"><br><input :value="post.body">
<button type="button" @click="changePost(post.id, post.title, post.body)">Применить</button></p>
</transition>
</li>
</ul>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'app',
data() {
return {
posts: [],
createTitle: '',
createBody: '',
visiblePostID: '',
}
},
changePost(id, title, body) {
axios.put('http://jsonplaceholder.typicode.com/posts/' + id, {
title: title,
body: body
})
}
}
</script>
Solution
To add to @Riddhi's answer, you could use v-model
on those inputs with temporary variables so that the model is not modified until the PUT
-request is confirmed successful:
Add temporary data properties to hold the
<input>
values from the template:// template <transition v-if="visiblePostID === post.id"> <input v-model="tmpTitle" /> <input v-model="tmpBody" /> </transition> // script data() { return { tmpTitle: '', tmpBody: '' } }
Replace the edit-button's handler with a method (named
editPost()
), and pass to the method the current post's ID, title, and body, which will be stored in the temporary data properties declared above:// template <button @click="editPost(post.id, post.title, post.body)"> Изменить </button> // script methods: { editPost(id, title, body) { this.tmpTitle = title; this.tmpBody = body; this.visiblePostID = id; } }
Update
changePost()
to also take the currentpost
, which will be updated with the temporary data properties once thePUT
request is successful.// template <button type="button" @click="changePost(post, post.id, tmpTitle, tmpBody)"> Применить </button> // script methods: { async changePost(post, id, title, body) { const { status } = await axios.put("https://jsonplaceholder.typicode.com/posts/" + id, { title: title, body: body }); if (status === 200 /* HTTP OK */) { post.title = title; post.body = body; } } }
Answered By - tony19 Answer Checked By - Mildred Charles (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.