实现步骤
在vue组件的模板中,定义表格的基本结构。使用v-for指令从数据源中遍历渲染表格的行数据。其中,需要添加一个绑定click事件的行,用于触发行折叠效果。代码示例如下:<template> <div> <table> <thead> <tr> <th>姓名</th> <th>年龄</th> <th>身高</th> </tr> </thead> <tbody> <tr v-for="(item,index) in tabledata" :key="index"> <td>{{item.name}}</td> <td>{{item.age}}</td> <td>{{item.height}}</td> <td class="fold" @click="foldrow(index)"></td> </tr> </tbody> </table> </div></template>
在组件的data属性中定义变量,用于判断表格中的行是否需要折叠。并且在初始化组件时,将所有行的状态设置为未折叠。代码示例如下:<script>export default { data() { return { tabledata: [ { name: '小明', age: '20', height: '180' }, { name: '小红', age: '19', height: '170' }, { name: '小刚', age: '22', height: '185' }, ], foldarr: [], }; }, created() { this.foldarr = new array(this.tabledata.length).fill(false); }, methods: { foldrow(index) { this.foldarr.splice(index, 1, !this.foldarr[index]); }, },};</script>
定义一个折叠行的组件。组件的模板中包含需要折叠的内容。当某一行需要折叠时,将隐藏内容渲染进来。组件代码示例如下:<template> <div v-show="foldarr[index]"> <p>{{item.intro}}</p> </div></template><script>export default { props: ['item', 'index', 'foldarr'],};</script>
在表格的body中,添加一个包含折叠行组件的tr。通过v-if指令判断当前行是否需要折叠,如果折叠,则渲染折叠行组件。代码示例如下:<template> <div> <table> <thead> <tr> <th>姓名</th> <th>年龄</th> <th>身高</th> </tr> </thead> <tbody> <tr v-for="(item,index) in tabledata" :key="index"> <td>{{item.name}}</td> <td>{{item.age}}</td> <td>{{item.height}}</td> <td class="fold" @click="foldrow(index)"></td> </tr> <tr v-for="(item,index) in tabledata" :key="index"> <td colspan="4" v-if="foldarr[index]"> <fold-row :item="item" :index="index" :foldarr="foldarr"></fold-row> </td> </tr> </tbody> </table> </div></template><script>import foldrow from '@/components/foldrow.vue';export default { components: { foldrow, }, data() { return { tabledata: [ { name: '小明', age: '20', height: '180', intro: '我是小明,今年20岁,身高180cm' }, { name: '小红', age: '19', height: '170', intro: '我是小红,今年19岁,身高170cm' }, { name: '小刚', age: '22', height: '185', intro: '我是小刚,今年22岁,身高185cm' }, ], foldarr: [], }; }, created() { this.foldarr = new array(this.tabledata.length).fill(false); }, methods: { foldrow(index) { this.foldarr.splice(index, 1, !this.foldarr[index]); }, },};</script>
对于样式的处理,可以使用css进行控制。通过设置.fold的width和height为0,使其无占用空间。通过设置.fold:before和.fold:after伪元素的样式,来实现折叠图标的切换。代码示例如下:<style lang="scss">.fold { position: relative; width: 0; height: 0; &:before, &:after { position: absolute; left: 50%; transform: translatex(-50%); content: ''; width: 6px; height: 6px; border-radius: 50%; background-color: #999; transition: all 0.2s ease; } &:before { top: 0; } &:after { bottom: 0; }}.fold.folded:before { transform: translatey(2px) translatex(-50%) rotate(45deg);}.fold.folded:after { transform: translatey(-2px) translatex(-50%) rotate(-45deg);}</style>
至此,我们已成功地实现了vue表格隐藏行折叠效果。通过这个方法,我们可以轻松地提升用户体验,让用户更加便捷地查看和管理表格数据。
以上就是vue表格隐藏行折叠效果怎么实现的详细内容。
