将标题重写为:将一个项目设置为true,其他所有项目设置为false的VueJS响应式元素
<p>我正在使用VueJS的组合API开发一个应用程序。
我已经设置了一个响应式元素,如下所示</p>
<pre class="brush:php;toolbar:false;">const sections = reactive({
section1: true,
section2: false,
section3: false,
section4: false,
section5: false,
section6: false
})</pre>
<p>当页面上的每个按钮被点击时,我想根据它们的布尔值显示和隐藏各个元素(以及其他许多操作)。
我可以为每个按钮编写一个函数,按照您在这段代码中看到的方式单独设置所有内容</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>这绝对有效,但这意味着我必须编写多个函数,实际上只有一个变化。
有没有更高效的方法来完成这个任务?
我觉得我应该能够用循环或者if语句来做到这一点,但我就是想不起来。
这是我在stackoverflow上的第一篇帖子,如果我没有提供足够的细节,请告诉我。</p>
你可以尝试像这样使用
Array.prototype.reduce和Object.entries来循环遍历sections的键/值对,并根据需要设置true/false,从而创建一个新的sections对象: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')"如果你发现需要直接修改属性,你可以使用
Array.prototype.forEach:const updateSections = (section) => { Object.keys(sections).forEach(key => { // 如果键与选定的section匹配,设置为true if (key === section) sections[key] = true; // 否则设置为false sections[key] = false; }); }希望对你有所帮助!