Trung Tran
Trung Tran

Reputation: 13771

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. 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. However, I also have a data model called contact, which gets used when the user wants to add a 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? Here is my vue component for reference:

<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>

Upvotes: 0

Views: 1268

Answers (1)

Egor Stambakio
Egor Stambakio

Reputation: 18156

Well, you already have addContact(contact) method defined in your template. 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. Or maybe I misunderstood your question?

Upvotes: 1

Related Questions