首页 > 解决方案 > 在 Blade 中获取 v-for 的循环索引

问题描述

我有一个 VueJS 组件,它通过 Laravel 控制器获取变量并通过 props[] 数组正确传递。其中一个视图文件内部有一个 v-for 循环,它迭代来自控制器的数据,并且流程工作得很好,除了一件事 - Operator(模型#1)和Comment(模型#2),所以基本上 - 我要做的是在运营商的表格中显示每个运营商有多少评论。我知道这种关系工作得很好,我试着在视图周围寻找,看起来数据是正确的var_dump$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>

请注意最后的评论里面<td>说 -

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

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

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

标签: phplaravelvue.js

解决方案


为什么不只在javascript中做呢

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

推荐阅读