Javascript 使用Alpine js与$dispatch进行组件通信

Javascript 使用Alpine js与$dispatch进行组件通信,javascript,alpine.js,Javascript,Alpine.js,我有一个“产品类别”下拉列表和可选输入字段,需要根据所选类别显示/隐藏这些字段$dispatch工作正常,但我无法在其他组件中接收值 选择类别 <div x-data="productCategories"> <select name="productCategory" class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 f

我有一个“产品类别”下拉列表和可选输入字段,需要根据所选类别显示/隐藏这些字段<代码>$dispatch工作正常,但我无法在其他组件中接收值

选择类别

<div x-data="productCategories">
    <select name="productCategory"
        class="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md"
        required
        @change="$dispatch('attribute', { brand: $event.target[event.target.selectedIndex].dataset.brand })"> 
        <option></option>
        <template x-for="[id, value] in Object.entries(categories)" :key="id">
            <optgroup :label="id">
                <template x-for="category in Object.values(value)" :key="category">
                    <option x-text="category.name" :data-brand="category.brand"
                        :value="category.name"></option>
                </template>
            </optgroup>
        </template>
    </select>
</div>
如果类别具有
brand:true

<div x-data="{ brand: ''}">
                                    
    <div class="col-span-3 sm:col-span-2" x-show="???">
        <label for="productBrand" class="block text-sm font-medium text-gray-700">
            Brand
        </label>
        <div class="mt-1 flex rounded-md shadow-sm">
            <input type="text" name="productBrand"
                class="focus:ring-indigo-500 focus:border-indigo-500 flex-1 block w-full rounded-md sm:text-sm border-gray-300">
        </div>
    </div>

</div>

烙印

我不确定在这种情况下,组件如何相互通信。如对本准则有任何指导或反馈,将不胜感激。
$dispatch
工作正常,但我无法在
x-show
中接收特定于属性的
布尔值
,或者在
模板中接收
x-if

我认为类似的东西应该从事件中获取数据并将其设置为组件状态



然后您可以使用
x-show=“brand”

我认为类似的东西应该从事件中获取数据,并将其设置为组件的状态



然后您可以使用
x-show=“brand”

谢谢雨果!很好用。谢谢雨果!那很好用。
<div x-data="{ brand: ''}">
                                    
    <div class="col-span-3 sm:col-span-2" x-show="???">
        <label for="productBrand" class="block text-sm font-medium text-gray-700">
            Brand
        </label>
        <div class="mt-1 flex rounded-md shadow-sm">
            <input type="text" name="productBrand"
                class="focus:ring-indigo-500 focus:border-indigo-500 flex-1 block w-full rounded-md sm:text-sm border-gray-300">
        </div>
    </div>

</div>