如何摆脱输入值的问题?

问题描述 投票:3回答:2

我有值post.titlepost.body,我需要在更改文本输入中的值之后,将其保存在数据中,以便稍后我可以使用这些新值供用户在API上编写(PUT请求)。我怎样才能做到这一点?

Screenshot the of the app

这是我的代码 -

<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>
javascript vue.js vuejs2 axios
2个回答
1
投票

要添加到@Riddhi的答案,您可以在具有临时变量的输入上使用v-model,以便在确认PUT-request成功之前不会修改模型:

  1. 添加临时数据属性以保存模板中的<input>值: // template <transition v-if="visiblePostID === post.id"> <input v-model="tmpTitle" /> <input v-model="tmpBody" /> </transition> // script data() { return { tmpTitle: '', tmpBody: '' } }
  2. 用一个方法(名为editPost())替换编辑按钮的处理程序,并将当前帖子的ID,标题和正文传递给方法,该文件将存储在上面声明的临时数据属性中: // 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; } }
  3. 更新changePost()以获取当前的post,一旦PUT请求成功,将使用临时数据属性更新。 // 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; } } }

demo


2
投票

对于双向数据绑定,您应该使用v-model。阅读here

<transition v-if="visiblePostID === post.id">
  <p>
    <input v-model="post.title">
    <br>
    <input v-model="post.body">

    <button type="button" @click="changePost(post.id, post.title, post.body)">Применить</button>
  </p>
</transition>
© www.soinside.com 2019 - 2024. All rights reserved.