Using this code, how to expand and collapse.. toggle all el-collapse-items of ElementPlus Vue3 Library with a single button ?
<template>
<div >
<el-collapse v-model="activeName" accordion>
<el-collapse-item title="Consistency" name="1">
<script lang="ts" setup>
import { ref } from 'vue'
const activeName = ref('1')
</script>
https://element-plus.org/en-US/component/collapse.html#accordion
CodePudding user response:
Take a look at following snippet pls :
const { ref } = Vue
const app = Vue.createApp({
setup() {
const items = ref([{id: 1, title: "first", text: "aaaaaaaaaaaa"}, {id: 2, title: "second", text: "bbbbbbbbbbbb"}, {id: 3, title: "third", text: "ccccccccccc"}])
const activeName = ref([1]);
const toggleAll = () => {
activeName.value = activeName.value.length === items.value.length
? []
: items.value.map(i => i.id)
}
return { items, activeName, toggleAll };
},
})
app.use(ElementPlus);
app.mount('#demo')
<link rel="stylesheet" href="//unpkg.com/element-plus/dist/index.css" />
<script src="//unpkg.com/vue@3"></script>
<script src="//unpkg.com/element-plus"></script>
<div id="demo">
<div >
<el-button type="primary" text bg @click="toggleAll">toggle all</el-button>
</div>
<div >
<el-collapse v-model="activeName" accordion>
<el-collapse-item v-for="item in items" :key="item.id" :title="item.title" :name="item.id">
<div>
{{ item.text }}
</div>
</el-collapse-item>
</el-collapse>
</div>
</div>
CodePudding user response:
You can not do this in the accordion mode. As documentations says:
In accordion mode, only one panel can be expanded at once
To do this, you have to remove the accordion prop and change the activeName value to an array, just like in the documentation:
const activeNames = ref(['1'])
To expand/collapse all items you can create a function that will change the value of activeNames to contain all the names of el-collapse-item components or to be empty, e.g
toggleElements() {
if(activeName.value.length) {
activeName.value = [];
} else {
activeName.value = ['1', '2', '3', ...];
}
}