I have a large component, with lots of boolean reactive states and each DOM element has to change 4-5 of them whenever a button is clicked. MWE:
<button @click="state.val1 = false; state.val2 = false; state.val3 = false">click me</div>
<p>{{state.val1}}</p>
<p>{{state.val2}}</p>
<p>{{state.val3}}</p>
button is an example of such DOM elements and it gets confusing quickly so I was wondering if there is a better, cleaner way of doing that.
I've tried:
<button @click="state.val1, state.val2 = false">
and
<button @click="state['val1', 'val2'] = false">
both of which only change the second object val2.
Probably best to write a generic method:
const myObj = {
state: {
key1: false,
key2: true,
key3: false
}
};
function changeState(name, keys, newVal) {
Object.keys(this[name]).forEach(key => {
if (keys.includes(key)) {
this[name][key] = newVal;
}
})
}
changeState.call(myObj, 'state', ['key1', 'key2', 'key3'], false);
console.log(myObj);
changeState.call(myObj, 'state', ['key1', 'key3'], true);
console.log(myObj);
So in Vue, you'd get something like:
<button @click="changeState('state', ['key1', 'key2', 'key3'], false)">