【问题标题】:Component communication with $dispatch using Alpine js使用 Alpine js 与 $dispatch 进行组件通信
【发布时间】:2021-03-18 16:49:01
【问题描述】:

我有一个产品类别下拉列表和可选输入字段,需要根据所选类别显示/隐藏。 $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>

productCategories 存储如下:

categories: {
    "Family": [{
            "name": "Health & Beauty",
            "brand": true,
            "size": false
        },
        {
            "name": "Baby & Kids",
            "brand": true,
            "size": true
        }
....

如果类别有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-showtemplate 中接收特定属性booleanx-if

【问题讨论】:

    标签: javascript alpine.js


    【解决方案1】:

    我认为这样的事情应该从事件中获取数据并将其设置为组件的状态。

    <div x-data="{ brand: ''}" @attribute.window="brand = $event.detail.brand">
    

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

    【讨论】:

      猜你喜欢
      • 2020-12-25
      • 1970-01-01
      • 2021-04-11
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 2019-02-09
      • 1970-01-01
      相关资源
      最近更新 更多