jantinnerezo / livewire-range-slider

MIT License
14 stars 20 forks source link

Programmatically setting `$range` doesn't change slider handles #11

Closed SturmB closed 2 years ago

SturmB commented 2 years ago

I've mostly gotten the hang of working with this component. However, one problem I'm now running into is setting the slider handles to specific values in the Livewire component's mount() method. I attempt to set it to specific values; however, the handles on the slider remain at their values beforehand.

Here's the class portion of the component:

class TierSlider extends Component
{
    public array $options = [
        "start" => [1, 4],
        "step" => 1,
        "range" => [
            "min" => [1],
            "max" => [4],
        ],
        "connect" => true,
        "behaviour" => "tap-drag",
        "pips" => [
            "mode" => "values",
            "stepped" => true,
            "density" => 100,
            "values" => [1, 2, 3, 4],
        ],
    ];
    public array $range;
    public int $armorId;

    public function render()
    {
        return view("livewire.tier-slider");
    }

    public function mount(Request $request)
    {
        $this->range = [
            "min" => "2",
            "max" => "3",
        ];
    }

    public function onChange(Request $request)
    {
        $this->emit("updateShoppingList", [
            "armorId" => $this->armorId,
            "minTier" => intval($this->range["min"]),
            "maxTier" => intval($this->range["max"]),
        ]);
    }
}

And here's the view portion:

<div class="m-6">
    <x-range-slider :options="$options" wire:model="range.min,range.max" wire:click="onChange" />
</div>

The handles after a refresh:

Handles at 1 and 4

SturmB commented 2 years ago

I just realized my faux pas. I didn't take into account $options' "start" value.

Here's the correct mount() method, along with the actual session data that I intend to use:

    public function mount(Request $request)
    {
        $armorAndTiers = $request
            ->session()
            ->get("armors.{$this->armorId}", ["minTier" => 1, "maxTier" => 4]);
        $this->options["start"] = array_values($armorAndTiers);
        $this->range = [
            "min" => strval($armorAndTiers["minTier"]),
            "max" => strval($armorAndTiers["maxTier"]),
        ];
    }