VueJS如何显示/隐藏项目列表中最接近的隐藏元素

时间:2019-10-30 09:07:33

标签: javascript vue.js vuejs2

如何通过单击vue中的按钮来显示/隐藏最接近的div?

我说我有一个物品清单,每个物品都有一些隐藏的细节

<ul>
   <li v-for="item in items" :key="item.id">
     <div>
         <p>{{item.text}}</p>
         <button @click="showDetails(item)">Show details</div>
         <div class="details" :class="isVisible ? activeClass : 'hidden'">Some hidden details</div>
     </div>
   </li>
</ul>

然后我做

data() {
   return {
      items: [ // a bunch of item objects here]
      isVisible: false,
      activeClass: 'is-visible'
  }
},
methods: {
   showDetails(item) {
       this.isVisible = item;
   }
}

现在,当我单击“ showDetails”按钮时,所有类为.details的div都将打开并获得.is-visible类,但我只想与该项目最接近的div被显示。出于某种原因,我认为这很简单,但是我无法使其正常工作。

我该如何实现?

3 个答案:

答案 0 :(得分:0)

只需将“ isVisible”变量存储在“项目”内

<ul>
   <li v-for="item in items" :key="item.id">
     <div>
         <p>{{item.text}}</p>
         <button @click="showDetails(item)">Show details</div>
         <div class="details" :class="item.isVisible ? activeClass : 'hidden'">Some hidden details</div>
     </div>
   </li>
</ul>




data() {
   return {
      items: [ // a bunch of item objects here]
      isVisible: false,
      activeClass: 'is-visible'
  }
},
methods: {
   showDetails(item) {
       item.isVisible = !item.isVisible;
       this.$forceUpdate();
   }
}

答案 1 :(得分:0)

为列表项创建一个包含所有逻辑本身的新组件会更加清楚。像这样:

// ListItem.vue
<template>
     <div>
         <p>{{text}}</p>
         <button @click="toggleVisibility">Show details</button>
         <div class="details" v-show="isVisible">Some hidden details</div>
     </div>
</template>

<script>
props: {
    text: String
},
data() {
    return {
      isVisible: false
  }
},
methods: {
  toggleVisibility() {
    this.isVisible = !this.isVisible
  }
}

</script>

并在您的父组件中:

<ul>
   <li v-for="item in items" :text="item.text" :key="item.id" is="list-item" /></li>
</ul>




data() {
   return {
      items: [ // a bunch of item objects here]
  }
}

答案 2 :(得分:0)

尝试

<template>
  <ul>
    <li v-for="(item, i) in items" :key="item.id">
      <div>
        <p>{{item.text}}</p>
        <button @click="showDetails(i)">Show details</button>
        <div class="details" :class="i == active ? activeClass : 'hidden'">Some hidden details</div>
      </div>
    </li>
  </ul>
</template>

<script>
export default {
  data() {
    return {
      items: [],
      activeClass: 'is-visible',
      active: null
    };
  },
  methods: {
    showDetails(i) {
      this.active = i;
    }
  }
};
</script>