简体   繁体   中英

Values ​stimulus js don't working a single escope of a controller

code example below:

<div class="form-floating mb-3" data-controller="home">
    <input type="text"
           class="form-control autocomplete-input"
           id="city" placeholder="Vila Mariana"
           data-home-target="district"
           data-action="keyup->home#autoComplete" />
    <label for="city">Bairro</label>
    <div class="autocomplete-body">
        <ul>
            {#for state in states}
                <li data-home-states-value="{state.uf}"
                    data-home-name-value="{state.name}"
                    data-action="click->home#selectItem">
                    {state.name}
                </li>
            {/for}
        </ul>
    </div>
</div>

The ul:li element is already inside a data-controller=home scope but it fails to capture the value of li. It only works if I declare:

{#for state in states}
    <li
        data-controller="home"
        data-home-states-value="{state.uf}"
        data-home-name-value="{state.name}"
        data-action="click->home#selectItem">
        {state.name}
    </li>
{/for}

I believe by design is must be in the same element as the controller definition.

Looking at the values documentation , It is purposefully put in the same element as the controller definition.

Where as the in the targets documentation , the targets are put in child elements.

I was having the same issue as you; the above is the conclusion I came to after way too much googling, and messing around with my own code. Though, I was unable to find a concrete definition anywhere on if this is expected behavior.

If you want to access that data you always define a target, or multiple, and access the data on that.

Setting in html:

data-home-target="abc"

Assign in controller:

static targets = ["abc"]

Access in controller:

this.abcTarget.dataset['dataname']

It looks like you might want to be accessing the data on an event click?

You could also do this in the event handler:

event.target.dataset['dataname']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM