如何在 v-for 循环中单独渲染所选的 class

How to individually render just the chosen class in a v-for loop

我正在编写一些实践代码,其中将显示客户帐户和卡的列表(见附图)。

每个 "Accounts" 包含多个 "Cards",我希望此程序显示指定帐户包含的卡片。例如,如果我单击按钮 "Account 1",则应仅显示帐户 1 中存储的卡。

但是,当我点击任何一个账户按钮时,所有的卡片都会显示出来(见附图)

我打算通过设置一个布尔变量并让卡片信息仅在布尔值为 true 时显示,来设计 v-for 循环以仅显示所选帐户的卡片,但正如您从输出屏幕截图中看到的那样,这显然不起作用。

我做错了什么,我如何让这个程序按照我描述的方式运行?

这是我的代码。

(v-for循环部分)

 <!-- If there is data for accounts, print it all out and then show the separate ID the user clicks on -->
            <div class="account-card-list"  v-for="(account,index) in accountsData" :key="account.id">
                <ul>
                    <li>
                        <span class="account" @click="clickAccountBtn(account.id)"  v-if="account.accountId == account.accountId"> 
                          Account {{index+1}}: 
                        </span>    
                        <span v-if="!accountBtnExpanded"> &nbsp; (← Click to expand)</span>
                        <span v-else> &nbsp; (← Click to fold)</span>
                        <br>
                        <br>
                        <ul v-if="accountBtnExpanded">
                            <li class="myList" v-for="(card,index) in cardsData" :key="card.id">
                                <span class="card" @click="getCardInfo(card.id)" v-if="card.accountId == account.id ">  
                                  <span class="cardBtn" @click="clickCardBtn()">Card {{index+1}} </span> &nbsp; &nbsp;  {{ card }}    
                                  <span v-if="cardBtnChosen">
                                    <br>
                                    <span class="cardInfo">CARDINFO:</span> {{ cardData }}
                                  </span> 
                                </span>                         
                            </li>
                            <ul>
                                <br>
                                <li ></li>
                            </ul>
                        </ul>
                    </li>
                </ul>
            </div>

这就是 clickAccountBtn(account.id) 方法的工作原理。

methods: {
      clickAccountBtn(accountId){
        if(this.accountBtnExpanded == false){
          this.accountBtnExpanded = true;
          this.findAccount(accountId);
        } else {
          this.accountBtnExpanded = false; 
        }
      },

使用数组保存您选择的帐户。

在数据中

selectedIds:[]

在模板中

<ul v-if="selectedIds.includes(account.id)">

然后,在您的点击处理程序中,切换数组中的项目 ID。

clickAccountBtn(accountId) {
  const idx = this.selectedIds.indexOf(accountId);
  if (idx > -1) {
    this.selectedIds.splice(idx, 1);
  }
  else {
    this.selectedIds.push(accountId);
  }

您也可以使用 objectset,甚至只限制一个 id,但一般方法仍然相同。