Rewrite the title to: VueJS responsive element with one item set to true and all others set to false
P粉786800174
2023-08-28 20:55:03
<p>I am developing an application using VueJS's composition API.
I've set up a responsive element as shown below</p>
<pre class="brush:php;toolbar:false;">const sections = reactive({
section1: true,
section2: false,
section3: false,
section4: false,
section5: false,
section6: false
})</pre>
<p>When each button on the page is clicked, I want to show and hide the individual elements (among many other operations) based on their boolean values.
I could write a function for each button that sets everything up individually as you see in this code</p>
<pre class="brush:php;toolbar:false;">const section1Button= () => {
sections.section1 = true,
sections.section2 = false,
sections.section3 = false,
sections.section4 = false,
sections.section5 = false,
sections.section6 = false
}
const section2Button= () => {
sections.section1 = false,
sections.section2 = true,
sections.section3 = false,
sections.section4 = false,
sections.section5 = false,
sections.section6 = false
}</pre>
<p>This definitely works, but it means I have to write multiple functions with really only one change.
Is there a more efficient way to accomplish this task?
I feel like I should be able to do this with a loop or an if statement, but I just can't think of it.
This is my first post on stackoverflow, please let me know if I haven't provided enough details. </p>
You can try using
Array.prototype.reduce
andObject.entries
like this to loop through the key/value pairs ofsections
and set them as neededtrue
/false
, thus creating a newsections
object:If you find that you need to modify the properties directly, you can use
Array.prototype.forEach
:Hope it helps!