来自获取数据的 Alpine JS 数据绑定组件

Alpine JS data binding component from fetched data

如何将获取的响应中的数据绑定到组件?

我的目标是检查用户当前的 deliveryProvider(从 firestore 获取)是否与给定的提供商名称匹配?

<template x-for="(provider, index) in Object.values(deliveryProviders.providers)" :key="provider">
<div>
    <label>
        <div class="relative flex justify-between border border-b-0 border-gray-200 p-3 md:pl-4 md:pr-6"
            :class="{
                'rounded-tl-md rounded-tr-md' : index === 0, 
                'rounded-bl-md rounded-br-md border-b': (Object.values(deliveryProviders.providers).length == index+1)}">
            <div class="text-sm flex cursor-pointer">
                <input name="deliveryProviders" type="checkbox" :value="provider.name"
                    class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 rounded"
                    :checked="user.deliveryProvider.includes(provider.name)">
                <div class="ml-3">
                    <div class="font-medium text-gray-900" x-text="provider.name"></div>
                    <div class="text-sm block text-gray-500" x-text="provider.description">
                    </div>
                </div>
            </div>
        </div>
    </label>
</div>

这种方法导致 Cannot read property 'includes' of undefined

使用您的代码段

您的脚本正在尝试加载,而 deliveryProviders 未定义。不让。

<div x-if="deliveryProviders !== undefined">
  <template x-for="(provider, index) in Object.values(deliveryProviders.providers)" :key="provider">
    <div>
      <label>
        <div class="relative flex justify-between border border-b-0 border-gray-200 p-3 md:pl-4 md:pr-6"
            :class="{
                'rounded-tl-md rounded-tr-md' : index === 0, 
                'rounded-bl-md rounded-br-md border-b': (Object.values(deliveryProviders.providers).length == index+1)}">
            <div class="text-sm flex cursor-pointer">
                <input name="deliveryProviders" type="checkbox" :value="provider.name"
                    class="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 rounded"
                    :checked="user.deliveryProvider.includes(provider.name)">
                <div class="ml-3">
                    <div class="font-medium text-gray-900" x-text="provider.name"></div>
                    <div class="text-sm block text-gray-500" x-text="provider.description">
                    </div>
                </div>
            </div>
        </div>
      </label>
    </div>
  </template>
</div>

解决方案解释

上面的代码片段使用 AJAX 通过获取接口从服务器请求数据。唯一的问题是没有任何东西告诉 AlpineJS 脚本等待数据填充。放置 x-if 逻辑将跳过有问题的代码,直到加载其依赖的变量。