Vuex dealing with duplicated repeated code

I use Vuex with some mutations. The code below may look useless because I’ve shorten it down quite a bit. The point is that I have duplicate code. I’ve read that I can’t use a Vue mixin in Vuex.

What is the best approach for dealing with duplicate code like this?

const store = new Vuex.Store({
    state: {
        // Stuff
    },
	mutations: {
		cellStepLeft: (state) => {
            // Do stuff
			let cell = document.querySelector(`[data-row="${active.row}"][data-col="${active.column}"]`);
			cell.focus();
		},
		cellStepRight: (state) => {
            // Do stuff
			let cell = document.querySelector(`[data-row="${active.row}"][data-col="${active.column}"]`);
			cell.focus();
		},
		cellStepDown: (state) => {
            // Do stuff
			let cell = document.querySelector(`[data-row="${active.row}"][data-col="${active.column}"]`);
			cell.focus();
		},
		cellStepUp: (state) => {
            // Do stuff
			let cell = document.querySelector(`[data-row="${active.row}"][data-col="${active.column}"]`);
			cell.focus();
		}
	}
});

Vuex is intended for state only. You shouldn’t be accessing element on the DOM in it. That should be done on the component level. To reduce duplicate code, create utility functions.

1 Like