【问题标题】:Show specific div `@click` in a loop in vuejs and laravel在 vuejs 和 laravel 的循环中显示特定的 div `@click`
【发布时间】:2018-11-21 03:17:45
【问题描述】:

我试图在点击时显示隐藏的潜水,但是我在使用循环时遇到了麻烦,其中我的所有 div 都是动态的。当我单击按钮时,它显示所有 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 是-

<script>
  var vm = new Vue({
    el: '#myApp',
    data: {
      isActive: true,
    },

    methods: {
      myFilter: function (event){
        this.isActive = !this.isActive;
      }
    }
  })
</script>

【问题讨论】:

  • 好吧,使用组件。那样的话,每个组件都会有它自己的状态。
  • 伙计,这个问题的轻微变体一遍又一遍地出现。 Here is one way.

标签: javascript jquery laravel vue.js toggle


【解决方案1】:

如果您不想将其移动到它自己的组件中,那么您将需要一个唯一标识符来显示循环中的哪个 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】:

    item 数组是在刀片中渲染的,所以当它到达前端时,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>
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-10
      • 1970-01-01
      • 2021-07-05
      • 1970-01-01
      • 1970-01-01
      • 2016-12-17
      • 2015-11-19
      • 1970-01-01
      相关资源
      最近更新 更多