Display and hide of vue list items

//数据
data() {
    
    
    return {
    
    
      isShow:null,
      menuTitle:[
        {
    
    
          bigTitle:'宠物商店',
          smallTitle:['宠物','宠物用品']
        },
        {
    
    
          bigTitle:'宠物服务',
        },
        {
    
    
          bigTitle:'个人中心',
          smallTitle:['商品订单','我的订单','我的评价']
        },
        {
    
    
          bigTitle:'关于我们',
        },
        {
    
    
          bigTitle:'帮助',
          smallTitle:['常见问题','联系我们','使用条款']
        }
      ]
    }
  },

The first method: by adding fields to each piece of data
Insert picture description here

Add a click event to the place where each item is clicked, and pass the current list item as a parameter
. Write the click event in the methods:
Insert picture description here

methods:{
    
    
    show(item){
    
    
      if(!item.isShow){
    
    
        this.$set(item,'isShow',false)
        item.isShow = !item.isShow
      }else{
    
    
        item.isShow=!item.isShow
      }
    }
    
  }

First, determine whether the list item has this field, if not, add the field through this.$set, and then reverse it, if there is this field, reverse it directly.

this.$set (the array or object you want to add data to,'field name', field value)

Finally, control the display and hide of the code block through v-show

<li  v-for="(item) in menuTitle" :key='item.id'>
      <a href="javascript:;" @click="show(item)">{
    
    {
    
    item.bigTitle}}<i v-if="item.smallTitle"></i></a>
      <transition name="ul">
        <ul v-show="item.isShow">
          <li v-for="rows in item.smallTitle" :key="rows.id"> <a href="">{
    
    {
    
    rows}}</a></li>
        </ul>
       </transition>
    </li>

Insert picture description here

The second method: Set an attribute
in data Set an attribute thisIndex in data, and give an initial value of -1 or null:

Insert picture description here

When writing a click event, pass the subscript of the current item as a parameter:

Insert picture description here

In the click event, when thisIndex is empty, assign the subscript of the current item to it, and when it is not empty, clear thisIndex:
Insert picture description here

But this method has a bug, it can only control the display and hide of one element. After all, thisIndex is still global. It will cause problems when you want to expand two at the same time, so it is better to use the first method of adding fields to the data.

Reference article: https://blog.csdn.net/CXJ_9280/article/details/92792418

Guess you like

Origin blog.csdn.net/d1063270962/article/details/113915834