Home  >  Q&A  >  body text

Rewrite the title to: VueJS responsive element with one item set to true and all others set to false

<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>
P粉786800174P粉786800174417 days ago507

reply all(1)I'll reply

  • P粉111627787

    P粉1116277872023-08-29 00:57:11

    You can try using Array.prototype.reduce and Object.entries like this to loop through the key/value pairs of sections and set them as needed true/false, thus creating a new sections object:

    const updateSections = (section) => {
      sections = Object.entries(sections).reduce((acc, [key, value]) => {
        // 如果键与选定的section匹配,设置为true
        if (key === section) return { ...acc, [key]: true };
        // 否则设置为false
        return { ...acc, [key]: false };
      }, {});
    }
    
    // 以你想要的方式触发updateSections来更新特定的section
    v-on:click="updateSections('section1')"

    If you find that you need to modify the properties directly, you can use Array.prototype.forEach:

    const updateSections = (section) => {
      Object.keys(sections).forEach(key => {
        // 如果键与选定的section匹配,设置为true
        if (key === section) sections[key] = true;
        // 否则设置为false
        sections[key] = false;
      });
    }

    Hope it helps!

    reply
    0
  • Cancelreply