代码之家  ›  专栏  ›  技术社区  ›  Rashed Hasan Vijayaragavan

在Vuejs和Laravel中的循环中显示特定的div`@click`

  •  0
  • Rashed Hasan Vijayaragavan  · 技术社区  · 6 年前

    我试图在点击时显示隐藏的潜水,但是,我在使用一个循环时遇到了麻烦,在这个循环中我的所有潜水都是动态的。当我单击按钮时,它显示所有的DIV,但我想在单击时显示特定的单个DIV。我试过这样的东西-

    index.blade.php文件

    <div class="col-md-12" id="questionsection">
      @foreach ($data['a'] as $row)
        <div class="row">
          <div class="col-sm-2"></div>
          <div class="col-sm-10">
             <button @click='myFilter($event)'>Comment</button>
             <div v-bind:class="{ noActive: isActive }">
                <form action="#" method="POST">
                  <textarea class="textarea" name="answer"></textarea>
                  <button>Save</button>
                </form>
             </div>
           </div>
         </div>
       @endforeach
    </div>
    

    .noactive显示:无

    在Vuejs script IS

    <script>
      var vm = new Vue({
        el: '#myApp',
        data: {
          isActive: true,
        },
    
        methods: {
          myFilter: function (event){
            this.isActive = !this.isActive;
          }
        }
      })
    </script>
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Rwd    6 年前

    如果您不想将它移动到它自己的组件中,那么您需要有一个唯一的标识符来显示循环中哪个DIV应该是活动的。您当前的设置无法知道单击了哪个DIV,您只需切换一个标志即可显示全部或全部DIV。

    解决此问题的一种方法是使用 foreach 循环,例如

    @foreach($data['a'] as $key => $row)
    

    然后,对于您的Vue实例,您可以有:

    <script>
        var vm = new Vue({
            el: '#myApp',
            data: {
                activeKey: null,
            },
    
            methods: {
                isActive(i) {
                    return this.activeKey === i;
                },
                toggleActive(i) {
                    this.activeKey = this.isActive(i) ? null : i;
                }
            }
        })
    </script>
    

    由于逻辑发生了轻微更改,因此需要更新刀片文件中的几行:

    <button @click='toggleActive($key)'>Comment</button>
    <div v-bind:class="{ noActive: isActive($key) }">   
    

    对于一个非常小的项目或者Vue没有被大量使用的项目,这种方法是很好的,但是,如果不是这样的话,我建议将它重构为一个组件。

    https://laracasts.com/series/learn-vue-2-step-by-step/episodes/7

        2
  •  0
  •   Christophe    6 年前

    项目数组在Blade中呈现,因此当它到达前端时,Vue不知道它。 此外,还有 isActive 对应用程序组件是全局的,因此它适用于所有项。

    您需要将数组作为一个属性传递给Vue组件,然后使用 v-for .

    <div class="row" v-for="(item, index) in {{ data['a'] }}" :key="index">
        <!-- same body of the loop as before -->
    </div>
    

    然后将索引和项添加到 myFilter($event, index, item) 函数更新数组中的相应项。

    您需要使用列出的方法之一更新项目 in the doc .