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
       }
    }
  }
})

<<:  SQL Server 系统资料库的介绍

>>:  [Vue2] 从初学到放弃 Day2

Day15 [实作] 使用 Socket.io 建立聊天室

实作 聊天室 server 端,使用 SSL 聊天室 client 端,使用 SSL 为什麽要使用 ...

Day25 - 针对 Metasploitable 3 进行渗透测试(6) - 使用 Meterpreter

Meterpreter 指令 昨天介绍了 Meterpreter 的指令列表,今天带大家来实作。 我...

[Day 21] 使用 Coroutine SendChannel 处理非同步工作

系统除了即时接受及回应使用者请求,也需要执行各种非同步工作,例如背景排程及寄送讯息通知…等。在实作上...

[30天 Vue学好学满 DAY9] v-if & v-show

v-if 条件式渲染 :true -> 渲染 可使用於template标签中 可进行断判断: ...

Day 19 UItableView的练习 (3/3)

接下来我们可以对我们每笔资料向左滑动後,让他可以被删除 func tableView(_ table...