首页 > 解决方案 > 如何在 VueJS 中有一个作用域切换变量

问题描述

我来自 AngularJS 背景,其中 ng-repeat 有一个作用域变量,我试图弄清楚如何在不需要创建一个新组件的情况下实现类似的结果,这在很多情况下似乎有点矫枉过正。

例如:

<div class="item" v-for="item in items">
  <div class="title">{{item.title}}</div>

  <a @click="showMore = !showMore">Show more</a>

  <div class="more" v-if="showMore">
    More stuff here
  </div>
</div>

在 AngularJS 中,该代码会很好用,但是在 VueJS 中,如果您单击显示更多,它会导致变量为项目列表中的每个项目更新,无论如何要在 v-for 内创建一个局部范围变量without the need to make a new component?

showMore我可以通过将变量设置为@click="showMore = item.id"then来使其工作,v-if="showMore.id = item.id"但是对于应该更简单的东西来说,这似乎也太复杂了?该方法的另一个问题是您只能让一个项目显示更多,而不是允许一次切换显示多个项目。

我还尝试将items模型更改为包含item.showMore,但这又增加了更多复杂性,如果由于模型更改而需要更新单个项目,则会导致问题。

有没有更简单的方法呢?

标签: vue.jsvuejs2

解决方案


您对此有何看法:CODEPEN

<template>
  <div>
    <h1>Items</h1>
      <div v-for="item in items" 
          :key="item.id" 
          class="item"
      >
        
        {{item.name}} 
        
        <button @click="show=item.id">
          Show More
        </button>
        
        <div v-if="item.id == show">
          {{item.desc}}
        </div>
        
      </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [
        {id:1, name:"One", desc: "Details of One"},
        {id:2, name:"Two", desc: "Details of Two"},
        {id:3, name:"Three", desc: "Details of Three"}
      ],
      show: null
    };
  }
};
</script>

<style>
  .item{
    padding: 5px;
  }
</style>

推荐阅读