AlpineJS $persist - 每页保存一次选项

问题描述 投票:0回答:1

我有一个使用 AlpineJS 构建的选择下拉列表,一旦选择了选项,所选值当前就会保存到 sessionStorage 中。但是,这些选项的值根据这些选项可用的每个页面而有所不同。

问题是,如果用户在一个页面上选择一个选项,然后改变主意并访问具有不同选项的不同页面,则当选项不同时,保存在 sessionStorage 中的第一个选择的选项将填充到任何其他页面上。

这是代码:

x-data="{ charter: $persist('').using(sessionStorage).as('_x_charterlength') }"
<div
    x-data="{ open: false }"
    @click.away="open = false"
    class="relative flex-1"
    >
        <!-- Button -->

        <button @click="open = !open"
            class="flex items-center justify-between flex-1 w-full gap-2 px-4 py-2 text-left bg-white border border-gray-400 rounded-lg"
            :class="[charter === '' ? 'border-2 border-orange-500' : '']"

        >
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-geo-alt-fill" viewBox="0 0 16 16">
                <path d="M8 16s6-5.686 6-10A6 6 0 0 0 2 6c0 4.314 6 10 6 10m0-7a3 3 0 1 1 0-6 3 3 0 0 1 0 6"/>
            </svg>

            <span class="w-full ml-2 overflow-hidden text-sm text-gray-600 whitespace-nowrap"
                x-text="charter === '' ? 'Add charter length' : charter"
            ></span>
        </button>
        <div x-show="open"
            class="absolute left-0 z-50 w-full p-4 mt-2 text-sm bg-white rounded-md shadow-md"
            x-cloak
        >
            <ul class="overflow-auto [&>li]:text-gray-500 [&>li]:px-4 [&>li]:py-2 hover:[&>li]:bg-gray-100 [&>li]:cursor-pointer space-y-2"
            >
            {{ pricing }}
            {{ if half_day }}<li @click="charter = $el.textContent; open = false;" class=" whitespace-nowrap"><span>1/2 Day: </span><span class="font-bold">${{ half_day }}.00 </li>{{ /if }}
                {{ if three_quarter_day }}<li @click="charter = $el.textContent; open = false;" class="whitespace-nowrap"><span>3/4 Day: </span><span class="font-bold">${{ three_quarter_day }}.00 </li>{{ /if }}
                    {{ if full_day }} <li @click="charter = $el.textContent; open = false;" class="whitespace-nowrap"><span>Full Day: </span><span class="font-bold">${{ full_day }}.00 </li>{{ /if }}
            </ul>
            {{ /pricing }}
        </div>
        <div x-text="[charter == '' ? 'Choose charter length' : '']" class="mt-1 text-xs font-bold text-orange-500"></div>
    </div>

我的问题是: 如何将给定页面的所选选项保存在 sessionStorage 中,但如果他们访问具有相同下拉列表但选项不同的另一个页面,则将其删除?

javascript alpine.js persist
1个回答
0
投票

我自己能想到的最好的办法就是每次有人访问带有选项列表的页面之一时清除特定的 sessionStorage 项目。

也许有更好的东西。

sessionStorage.removeItem("_x_charterlength");

© www.soinside.com 2019 - 2024. All rights reserved.