【问题标题】:Getting v-for's loop index inside Blade在 Blade 中获取 v-for 的循环索引
【发布时间】:2020-12-14 22:51:00
【问题描述】:

我有一个 VueJS 组件,它通过 Laravel 控制器获取一个变量,并通过 props[] 数组正确传递。其中一个视图文件内部有一个 v-for 循环,它迭代来自控制器的数据,并且流程工作得很好,除了一件事 - Operator(模型#1)之间存在一对多的关系和Comment(模型#2),所以基本上 - 我要做的是在操作员的表格中显示每个操作员有多少 cmets。 我知道这种关系很好,我在视图周围尝试了var_dumping $comments$data,看起来数据是正确的。

这是列表视图的一部分,它迭代运算符并使用它们的数据创建一个表 -

...
...
<operator-listing
        :data="{{ $data->toJson() }}"
        :url="'{{ url('admin/operators') }}'"
        :comments="{{ $comments }}"
        inline-template>
<tbody>
<tr v-for="(item, index) in collection" :key="item.id" :class="bulkItems[item.id] ? 'bg-bulk' : ''">
<td class="bulk-checkbox">
<input class="form-check-input" :id="'enabled' + item.id" type="checkbox" v-model="bulkItems[item.id]" v-validate="''" :data-vv-name="'enabled' + item.id"  :name="'enabled' + item.id + '_fake_element'" @click="onBulkItemClicked(item.id)" :disabled="bulkCheckingAllLoader">
<label class="form-check-label" :for="'enabled' + item.id">
</label>
</td>

<td>@{{ item.id }} </td>
<td>@{{ item.name }}</td>
<td>
<label class="switch switch-3d switch-success">
<input type="checkbox" class="switch-input" v-model="collection[index].enabled" @change="toggleSwitch(item.resource_url, 'enabled', collection[index])">
<span class="switch-slider"></span>
</label>
</td>

<td>@{{ item.rank }}</td>
<td>@{{ item.total_score }}</td>
<td>
<!-- 
     Here i am trying to do something like this -
     {{ count($comments->where('operator_id',$item_id)) }}
-->
</td>

请注意最后一个 &lt;td&gt; 里面的评论 -

<!-- 
     Here i am trying to do something like this -
     {{ count($comments->where('operator_id',$item_id)) }}
-->

$item_id 只是一个模型,在任何地方都没有真正定义。 由于我在此 &lt;td&gt; 中使用刀片模板 {{ }} 而不是 Vue,这意味着我无法从 Vue 的循环迭代中访问 {{ item.id }},我实际上需要为此检索 ->where 语句。

有没有办法将 Vue 的 v-for 循环中的 @{{ item.id }} 传递到刀片模板中?

  • 两个模型('Operator''Comment')都有 -&gt;belongsTo-&gt;hasMany(相对)工作正常的方法。

【问题讨论】:

    标签: php laravel vue.js


    【解决方案1】:

    为什么不只在javascript中做呢

    <td>
        @{{ comments.filter(comment => comment.operator_id === item.id).length }}
    </td>
    

    【讨论】:

    • 谢谢。唯一的原因是我是一名 PHP 开发人员,这是我的舒适区,所以有时在语言功能之间进行这些“跳跃”并不容易。
    • @GonrasKarols 我明白,即使是熟悉该语言的开发人员也会发生这种情况 - 有时它会发生 - 不用担心
    猜你喜欢
    • 1970-01-01
    • 2018-04-06
    • 1970-01-01
    • 2017-08-13
    • 2013-04-10
    • 2018-09-15
    • 2012-08-20
    • 2013-03-19
    • 2019-04-06
    相关资源
    最近更新 更多