首页 > 解决方案 > 如何编辑作为属性传递的 vue 数据?

问题描述

我有一个 Vuex 数据存储,其中包含contacts. 我在 中显示该数组ContactList.vue,其中有一个导航到 CreateEditContact.vue 的“编辑”按钮(我将contact作为名为 的道具传递contactProp)。所有这些都有效,但众所周知,您不能直接编辑道具。我尝试检查模板为 时是否填充了道具created,并将其复制到contactindata但它不起作用。这样做的正确方法是什么?

联系人列表.vue

<template>
    <!-- ...redacted for brevity -->

    <!-- I'm reusing the same .vue for creating new and editing contacts -->

    <!-- edit contact button -->
    <v-btn text
           :to="{name: 'createEditContact',
                  params: {
                    action: 'edit',
                    id: contact.id,
                    contactProp: contact
                  }}">Edit</v-btn>

    <!-- new contact button --> 
    <v-btn
        :to="{ name: 'createEditContact', params: { action: 'create' } }"
        outlined
        rounded>New</v-btn>

</template>

CreateEditContact.vue

<template>
  <div>
    <h3>Create or Edit a Contact</h3>
    <v-form @submit.prevent="saveContact">
      <v-container>
        <v-row>
          <v-col>
            <v-text-field label="Name" v-model="contact.name" />
          </v-col>
          <v-col>
            <v-text-field label="Phone Number" v-model="contact.phone" />
          </v-col>
          <v-col>
            <v-text-field label="Extension" v-model="contact.extension" />
          </v-col>
          <v-col>
            <v-btn type="submit">Save</v-btn>
          </v-col>
        </v-row>
      </v-container>
    </v-form>
  </div>
</template>

<script>
    import axios from "axios";

    const options = {
        headers: { "Content-Type": "application/json" }
    };

    export default {
        name: "CreateEditContact",
        props: {
            action: {
                type: String,
                required: true,
                validator: value => ["create", "edit"].indexOf(value) !== -1
            },
            id: {
                required: false
            },
            // contactProp gets set correctly when editing...
            contactProp: {}
        },
        data() {
            return {
                // the empty contact (when creating a new contact)
                contact: {
                    id: 0,
                    name: "",
                    phone: "",
                    extension: "",
                    fullString: "",
                    telephoneUrl: ""
                }
            };
        },
        methods: {
            saveContact() {
                // redacted for brevity
            },
            created() {
                // when contactProp is populated, I need to use that... 
                // but contact is always empty when I try to edit one.
                // this next line isn't doing what I think it should.
                if (this.contactProp) this.contact = this.contactProp;
            }
        }
    };
</script>

标签: vue.jsvuejs2vue-componentvuex

解决方案


推荐阅读