结合 vuejs v-repeat 和 php foreach 循环?

Combining vuejs v-repeat and php foreach loop?

我目前正在使用 vue.js 通过它的 v-repeat 功能回显一堆项目。不幸的是,我还需要 运行 v-repeat 循环中的一个 php 函数,它接受一个参数($beerId)。

<div class="search-item" v-repeat="set: beers | chunk 4">
    <div class="row">
        <!-- Cycle through the data in "beer" -->
        <div v-repeat="beer: set">
            <div class="col-md-3">
                <h2>@{{{ beer.name }}}</h2>

                {{ auth()->user()->timesAddedBeer($beerId) }}
            </div><!-- /.col-md-3 -->
        </div><!-- v-repeat -->
    </div><!-- /.row -->
</div><!-- /.search-item -->

此块将数组分成 4 位,每行显示 4 个项目,每页显示 12 个项目。

我需要能够设置 $beerid 变量。我无法为其分配 beer.id javascript 值,因为 javascript 加载速度比 php 慢一点,并且 php 函数在 javascript 之前执行数据已加载。

我确实可以从 php 访问包含相同值的 $beers 数组,但这意味着我必须 运行 在某处进行 foreach 循环才能获取这些值,而且我已经有一个 v-repeat 循环。这样会变得混乱。

目前我觉得我运行别无选择。这也很难对外人解释,我已经简化了例子。如果您需要更多信息,请询问!如果有人能帮助我,我会很高兴。

我认为您不能(或不应该)按照您尝试编码的方式进行编码。由于您在 Vue 中拥有啤酒数据集,我建议您可以采用两种选择。

  1. 通过点击 AJAX 端点在 Vue 中动态加载啤酒计数(如果选项 #2 的操作成本太高,这将是我的首选方式)。

    <div class="search-item" v-repeat="set: beers | chunk 4">
        <div class="row">
            <!-- Cycle through the data in "beer" -->
            <div v-repeat="beer: set">
                <div class="col-md-3">
                    <h2>@{{{ beer.name }}}</h2>
    
                    @{{ timesAdded(beer.id) }}
                </div><!-- /.col-md-3 -->
            </div><!-- v-repeat -->
        </div><!-- /.row -->
    </div><!-- /.search-item -->
    
    <script>
    // This is Psuedocode for example's sake
    timesAddedBeer: function (id) {
        // Find the beer that we need by its id and return timesadded if it exists
        if (beer[id].timesAdded) return beer[id].timesAdded;
        // If timesadded doesn't exist lets get it and set it
        // this *should* trigger a data refresh and updated the html with the count
        $.post(id, 'endpoint', function(respone) {
            this.$set(beer[id].timesAdded, response.timesAdded);
        });
    }
    </script>
    
  2. 在将其传递给 Vue 之前循环遍历您的啤酒数据集并调用 timesAddedBeer 函数并将该值添加到您的数据集。