我有一个带有contacts
数组的Vuex数据存储。我在ContactList.vue
中显示该数组,在这里有一个“编辑”按钮,该按钮导航到CreateEditContact.vue(我将contact
作为名为contactProp
的道具传入)。所有这些都有效,但是众所周知,您不能直接编辑道具。我尝试检查模板为created
时是否填充了prop,然后将其复制到contact
中的data
中,但是它不起作用。 正确的方法是什么?
ContactList.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>