Only show associated data in v-for

筅森魡賤 提交于 2020-11-29 11:06:09

问题


I have the following code:

<template>
<div>
    <div v-for="title in titles">
        <h1>{{ title }}</h1>
        <a @click="showSub">Click Here</a>
        <div v-if="subshown">
            Shown
        </div>
    </div>
</div>
</template>

<script>
    export default {
        data() {
            return {
                subshown: false,
                titles: []
            }
        },
        methods: {
            showSub: function () {
                this.subshown = true;
                // do something more
            }
        }        
    }
</script>

When i now click on the Click Here Button, the associated subshown from the current title should be shown. At the moment, when i click on Click Here, all subshown are shown.

How to implement that only the associated is shown?


回答1:


Add a property called currentIndex then update it using the click event and use it in conditional rendering :

<template>
<div>
    <div v-for="(title,index) in titles">
        <h1>{{ title }}</h1>
        <a @click="showSub(index)">Click Here</a>
        <div v-if="currentIndex===index">
            Shown
        </div>
    </div>
</div>
</template>

<script>
    export default {
        data() {
            return {
                currentIndex:-1,
                titles: []
            }
        },
        methods: {
            showSub: function (index) {
              this.currentIndex=this.currentIndex===index?-1:index
                // do something more
            }
        }        
    }
</script>


来源:https://stackoverflow.com/questions/64894939/only-show-associated-data-in-v-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!