[英]How to override vuex store data
I have a reusable vue.js contact form component that could be used for creating new contacts or updating contacts. 我有一个可重复使用的vue.js联系人表单组件,可用于创建新联系人或更新联系人。 I have a store that keeps track of which contact a user wants to edit called
contactToEdit
and I assign it to a computed variable called contact
. 我有一个商店,它跟踪用户要编辑的联系人(称为
contactToEdit
并将其分配给一个名为contact
的计算变量。 However, I also have a data model called contact
, which gets used when the user wants to add a contact. 但是,我还有一个名为
contact
的数据模型,当用户想要添加联系人时会使用该数据模型。 Therefore, when I am using the component to add a contact, is there a way I can override the computed contact variable (since it will be undefined at this point)? 因此,当我使用组件添加联系人时,有没有办法可以覆盖计算出的联系人变量(因为此时将是未定义的)? Or can I conditionally tell the component to use the
contact
from the vuex store vs. the default contact modal? 或者,我可以有条件地告知组件使用的
contact
从vuex店与默认联系人模式? Here is my vue component for reference: 这是我的Vue组件供参考:
<template>
<form class="padded-form">
<div class="form-group">
<label for="">First Name</label>
<input type="text" class="form-control" id="" v-model="contact.first_name">
</div>
<div class="form-group">
<label for="">Last Name</label>
<input type="text" class="form-control" id="" v-model="contact.last_name">
</div>
<div class="form-group">
<label for="">Email</label>
<input type="text" class="form-control" id="" v-model="contact.contact_email">
</div>
<div class="form-group">
<label for="">Phone #</label>
<input type="text" class="form-control" id="" v-model="contact.contact_phone_number">
</div>
<div class="form-group">
<label for="">Notes</label>
<textarea class="form-control" id="" rows="4" v-model="contact.contact_notes"></textarea>
</div>
<div class="d-flex justify-content-center"><button class="btn btn-primary btn" v-if="adding" @click="addContact(contact)">Submit</button></div>
<div class="d-flex justify-content-center"><button class="btn btn-primary btn" v-if="editing" @click="saveContact(contact)">Save</button></div>
</form>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
data() {
return {
contact: {
first_name: '',
last_name: '',
contact_email: '',
contact_phone_number: '',
contact_notes: ''
}
}
},
computed: {
...mapGetters({
contact: 'contactToUpdate',
editing: 'editingContact',
adding: 'addingContact',
})
},
}
</script>
Well, you already have addContact(contact)
method defined in your template. 好了,您已经在模板中定义了
addContact(contact)
方法。 Inside this method you can commit your Vuex mutation which overwrites the 'contact' Vuex state property, so when you click a button the state is mutated and your contact
getter updates. 在此方法内,您可以提交您的Vuex突变,该突变将覆盖“联系人” Vuex状态属性,因此,当您单击按钮时,状态会发生突变,并且您的
contact
更新。 Or maybe I misunderstood your question? 还是我误解了你的问题?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.