Vue出一个展开 / 隐藏 功能

今天练习的主题是用Vue实现列表的展开与隐藏功能
会分为两个範例让大家做演练

图一

範例一

先将isShow默认为false
接着在function内判断当前的列表是否为false,是的话则往下执行内容
由于我想要动态操作功能,另外又写了一层判断式
判断当前列表的长度有没有大于三笔,有的话往下执行,下方有列for迴圈与forEach的写法,喜欢用哪种都行
若没有的话则接将列表指向testList

<template>  <div>    <div v-for='(item, index) in testList' :key="index">{{ item }}</div>    <div @click='isShow = !isShow'>{{ textSwitch }}</div>  </div></template><script>export default {  data () {    return {      dataList: [        { id: 0, test: '我是一段很长的文字1' },        { id: 1, test: '我是一段很长的文字2' },        { id: 2, test: '我是一段很长的文字3' },        { id: 3, test: '我是一段很长的文字4' },        { id: 4, test: '我是一段很长的文字5' },        { id: 5, test: '我是一段很长的文字6' }      ],      isShow: false    }  },  computed: {    testList () {      if (this.isShow === false) {        let testList = []        if (this.dataList.length > 3) {          this.dataList.forEach((item, index) => {            if (index < 3) {              testList.push(item)            }          })          // for (var i = 0; i < 3; i++) {          //   testList.push(this.dataList[i])          //   console.log(testList)          // }        } else {          testList = this.dataList        }        return testList      } else {        return this.dataList      }    },    textSwitch () {      if (this.isShow === false) {        return '显示更多'      } else {        return '收起'      }    }  }}</script>

範例二

若今天想要单独展开列表的话该如何去实现呢?!
大家心中会有一个小疑问,limit: -1,是什么意思?
这是因为index从0开始因此-1代表没有东西
举例:
展开id:2的列表,这时limit = 2,欲将id:2的列表给关闭,这时limit则会变回-1
不晓得这样解是大家有没有懂~
附上CodePen给大家试试

  <div id="app">    <ul class="mtree" v-for="(item, index) in dataList" :key="index" @click="clickItem(index)">      <li class="tree-node">        <h1>{{item.title}}</h1>        <p  v-show="index === limit">{{item.test}}</p>      </li>    </ul>  </div>    const app = new Vue({  el: '#app',    data: {      dataList: [        { id: 0, title: '我是标题1', test: '我是内文1' },        { id: 1, title: '我是标题2', test: '我是内文2' },        { id: 2, title: '我是标题3', test: '我是内文3' },        { id: 3, title: '我是标题4', test: '我是内文4' },        { id: 4, title: '我是标题5', test: '我是内文5' }      ],      limit: -1  },  methods: {    clickItem(index) {       if (index === this.limit) {         this.limit = -1       } else {         this.limit = index       }    }  }})

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章