Tengo un componente grande, con muchos states reactivos boolean y cada elemento DOM tiene que cambiar 4-5 de ellos cada vez que se hace clic en un botón. 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 es un ejemplo de tales elementos DOM y se vuelve confuso rápidamente, así que me preguntaba si hay una forma mejor y más limpia de hacerlo.
He intentado:
<button @click="state.val1, state.val2 = false">y
<button @click="state['val1', 'val2'] = false"> ambos solo cambian el segundo objeto val2 .
Probablemente sea mejor escribir un método genérico:
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);Entonces, en Vue, obtendrías algo como:
<button @click="changeState('state', ['key1', 'key2', 'key3'], false)">