【问题标题】:Vuejs- Get Object ID after POST Request In Current PageVuejs-在当前页面中POST请求后获取对象ID
【发布时间】:2020-12-01 18:42:24
【问题描述】:

我想在同一页面实现保存和编辑。当然,我有很多字段输入所以,我可以输入一些输入字段save没有重定向到另一个页面。

我想要的是在 POST 请求后获取当前 ID 所以,我可以使用 That IDPATCH request

Vuejs Code

<v-btn
    color="primary"
    v-if="isEdit === false"
    small
    :loading="loading"
    @click="save"
    >save</v-btn
>
<v-btn
    color="primary"
    small
    :loading="loading"
    @click="edit"
    v-if="isEdit === true"
    >edit</v-btn
>

In script

<script>
export default {
   data() {
        return {
          form: {},
          isEdit: false
       }
   },

     save() {
            this.loading = true;
            axios
                .post(`api/v1/partner/`, this.form)
                .then((res) => {
                    console.log(res);
                    this.isEdit = true;
                })
                .catch((err) => {
                    console.log(err.response);
                    this.loading = false;
                    this.snackbar.value = true;
                    this.$refs.form.validate(err.response.data);
                });
        },

        edit() {
            this.isEdit = true;
            axios
                .patch(`api/v1/partner/${this.form.id}/`, {
                })
                .then((res) => {
                    console.log(res);
                    // this.$router.push(`/partner/`);
                    this.loading = false;
                })
                .catch((err) => {
                    console.log(err.response);
                    this.loading = false;
                });
        },
}
</script>

感谢您的所有帮助。谢谢...

【问题讨论】:

  • 您的 API 对 POST 请求的响应是什么?是否包含新 ID?
  • @Phil,在POST request 之后,是的,我得到了新 ID。
  • 通常,人们使用PUT 来更新现有资源。 PATCH 就像是部分更新(例如,不是整个对象,只是选择属性)。
  • @Phil,是的,我知道这一点。非常感谢您的解决方案,它比我预期的要简单。 :)

标签: html vue.js vuetify.js


【解决方案1】:

假设您的 API 使用新 ID 从 POST 请求响应,您只需将其设置为您的 form 对象

axios.post("api/v1/partner/", this.form)
  .then(res => {
    console.log(res)
    this.isEdit = true
    this.form.id = res.data.id // assuming that's the right property name
  })

【讨论】:

  • 感谢随机陌生人投反对票。由于这已经是公认的答案,您能否发表评论,解释问题所在,以便我为未来的读者修复它?
猜你喜欢
  • 1970-01-01
  • 2021-09-09
  • 2021-05-01
  • 1970-01-01
  • 2020-06-24
  • 2018-09-12
  • 1970-01-01
  • 2011-07-13
  • 2014-04-16
相关资源
最近更新 更多