My Index.js from the Store Folder
import Vue from "vue";
import Vuex from "vuex";
import state from "../store/state";
import mutations from "../store/mutations";
import actions from "../store/actions";
Vue.use(Vuex);
export default new Vuex.Store({
state,
mutations,
actions,
});
The State.js File
/* eslint-disable */
import cats from "../data/cats.js";
import dogs from "../data/dogs.js";
export default {
cats,
dogs,
};
Actions.js Content
// method add pet -> dispatch action -> mutate -> state changes
export default {
addPet: ({ commit }, payload) => {
console.log("payload is", payload);
commit("appendPet", payload);
},
};
The Mutations.js Script
export default {
appendPet: (state, { specie, pet }) => {
console.log("specie and pet are", specie, pet);
state[specie].append(pet);
},
};
The Code in Home.vue
<template>
<div class="home">
<h1>Adopt a New Best Friend</h1>
<button @click="formShow" class="btn btn-primary">Add New Pet</button>
<b-form @submit.prevent="handleSubmit" v-if="showForm === true">
<b-form-group id="input-group-2" label="Pet's Name:" label-for="input-2">
<b-form-input
id="input-2"
v-model="formData.name"
type="text"
placeholder="Enter name"
required
></b-form-input>
</b-form-group>
<b-form-group id="input-group-3" label="Specie:" label-for="input-3">
<b-form-select
id="input-3"
v-model="formData.specie"
:options="['cats', 'dogs']"
required
></b-form-select>
</b-form-group>
<b-form-group id="input-group-2" label="Pet's Age:" label-for="input-2">
<b-form-input
id="input-2"
v-model="formData.age"
type="number"
placeholder="Enter Age"
required
></b-form-input>
</b-form-group>
<b-button type="submit" variant="primary">Submit</b-button>
<b-button type="reset" variant="danger">Reset</b-button>
</b-form>
</div>
</template>
<script>
import { mapActions } from "vuex";
export default {
name: "Home",
data() {
return {
showForm: false,
formData: {
age: 0,
specie: null,
name: "",
},
};
},
methods: {
...mapActions["appendPet"],
formShow() {
this.showForm = !this.showForm;
},
// mapActions and appendPet do not show on console
handleSubmit() {
console.log("hello this is the handle submit method");
const { specie, age, name } = this.formData;
console.log("specie , age and name are", specie, age, name);
const payload = { specie, pet: { name, age } };
this.appendPet(payload);
},
},
};
</script>
I am experiencing issues with my home.vue
. The template section works fine, but I'm unable to mutate the state as expected. When checking the console for mapActions
, it does not show any output. This leads me to believe that the appendPet
method responsible for mutating the state is not being called correctly, preventing the payload from reaching the Action.js
. The issue might lie with the execution of mapActions
while trying to call appendPet
.