One approach I've taken is creating a global error state using Vuex, which consists of an array containing objects representing all current errors.
const store = new Vuex.Store({
state: {
errors: []
},
getters: {
getErrors: state => state.errors
},
mutations: {
setError: (state, message) => {
state.errors.push({ error: true, message });
},
removeError: (state, i) => {
state.errors.splice(i, 1);
}
}
});
I have a component that dynamically displays all errors based on the Vuex state. My aim is to remove objects from the array where the error property is set to false. This property is controlled by the setError mutation and v-model within the component.
To achieve this, I'm attempting to watch for changes and remove the desired items from the array. However, it doesn't seem to be removing them immediately when the property changes to false. How can I fix this?
You can view a live demo here.
<template>
<div id="snackbar">
<v-snackbar
v-for="(error, index) in getErrors"
:key="index"
v-model="error.error"
color="red"
:right="true"
:timeout="2000"
:top="true"
>
{{ error.message }}
<v-btn dark text @click="removeError(index)">Close</v-btn>
</v-snackbar>
</div>
</template>
<script>
import { mapGetters, mapMutations } from "vuex";
export default {
name: "ErrorSnackbar",
computed: mapGetters(["getErrors"]),
methods: {
...mapMutations(["removeError"]),
removeError(i) {
this.$store.commit("removeError", i);
}
},
watch: {
getErrors: {
handler(newErrors) {
if (newErrors.length > 0) {
newErrors.forEach((error, i) => {
if (error.error === false) {
newErrors.splice(i, 1);
}
});
}
},
}
}
};
</script>