I'm still learning Vue and I can't understand why this error occurs.
Error: [vuex] Do not mutate vuex store state outside mutation handlers.
Here is my code:
const DATE_FORMAT = "DD-MM-YYYY";
Vue.filter("formatDate", function(value, dateFormat) {
dateFormat = dateFormat ? dateFormat : DATE_FORMAT;
if (value) {
return moment(String(value)).format(dateFormat);
}
});
Vue.component('list-component', {
props: ['projects'],
template:
`
<div>
<ul v-for="project in projects" :key="project.id">
<li v-for="(value, key) in project" :key="key">
{{ key }}: {{ value }}
</li>
<hr />
</ul>
</div>
`
});
const store = new Vuex.Store({
state: {
projects: [{
id: 1,
name: "super project",
startDate: "2014-09-01T08:18:28+02:00"
}, {
id: 2,
name: "extra project",
startDate: "2017-12-20T07:28:23.133+01:00"
}, {
id: 3,
name: "small project",
startDate: "2017-12-20T07:28:23.133+01:00"
}]
},
getters: {
allProjects: state => state.projects
},
strict: true
});
new Vue({
el: '#app',
computed: {
formattedProjects() {
var project = store.getters.allProjects;
project.forEach(project => {
project.startDate = this.$options.filters.formatDate(project.startDate);
});
return project;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.js"></script>
<script src="https://unpkg.com/vuex@3.0.1/dist/vuex.js"></script>
<script src="https://unpkg.com/vue@2.5.13/dist/vue.js"></script>
<div id="app">
<list-component :projects="formattedProjects"></list-component>
</div>
https://jsfiddle.net/9sn78n1h/2/
I can't use my filter in the component, because the property name can be different. In the example above it's startDate
, but in other data it could be addDate
, endDate
etc.
In the vuex store I need the startDate
in the format as it is, I don't want to mutate it.
I'm not sure that writing another getter in the vuex like allProjectsWithFormatedDate
is a good practice, but even so, it still yells about the mutating store.
So I create a local variable project
in my computed method formattedProjects()
and I don't know why I've got this error after changing it's value.
Can somebody help me to understand it and show the correct way to solve this problem?
I know I can set the strict
mode to false
to mute this error (and I should in production), but I belive there is a better way to solve this.