Should a Vuex store only contain the code for the state structure and how to modify that state (mutations, actions), or should it also include the actual state initialization and values?
I began contemplating this question when my state initialization code started becoming more complex, as I couldn't find a natural place within the Vuex architecture to integrate this code.
Consider the following store:
export default {
state: {
list: []
},
mutations: {
addItem(state, { item }) {
state.list.push(item);
}
}
}
If the list starts off empty, it works fine. But what if I have default values for the list and I want to store the list in LocalStorage to preserve its value between page loads?
const STORAGE_LIST_KEY = 'list';
const LIST_DEFAULT = [
{
id: 1,
name: 'item 1'
},
{
id: 33,
name: 'item 33'
}
];
function initializeList() {
let savedList = localStorage.getItem(STORAGE_LIST_KEY);
return savedList ? savedList : LIST_DEFAULT;
];
Is there a specific location in the Vuex store architecture where the initializeList()
function should be placed? (For example, in a Vue component, I would typically place initializeList()
within the methods
section of the component). Or is it possible that the store is solely responsible for the structure, while the initialization code should belong to the Vue components?