Selector changes in Vue.js: setting selected data for selectors and event selectors in loops
P粉821231319
P粉821231319 2023-09-11 09:59:53
0
1
672

I need to run jq-like functions in vuejs:

- html 
             @foreach($users as $user) 
                <td>
                    <selecter class="check-change" data-id="{{$user->id}}">
                        <opt @if($user->status == 'active') selected @endif value="active">Active</opt>
                        <opt @if($user->status == 'wait_confirm') selected @endif value="wait_confirm">Wait Confirm</opt>
                    <selecter>
                </td>`
- jq 
            `$('.check-change').on('change', function() {
                var new_value = this.value;
                -> send request update user (this.attr('data-id'))
            });

I'm stuck because I don't know how to check and add the selected attribute in vue js, nor how to get the user id and selected option when the user's selector changes.

Current code:

const items_status = [
{
    state: 'Active',
    abbr: 'active',
  },
  {
    state: 'Wait Confirm',
    abbr: 'wait_confirm',
  }
];
const selectedOption = ref({
    state: 'Wait Confirm',
    abbr: 'wait_confirm',
})
<tr
    v-for="user in users"
    :key="user.id"
    style="height: 3.75rem;"
    <td>
        <VSelect
            v-model="selectedOption"
            :hint="`${selectedOption.state}, ${selectedOption.abbr}`"
            :items="items_status"
            item-title="state"
            item-value="abbr"
            label="Select"
            persistent-hint
            return-object
            single-line
        />
    </td>
</tr>

P粉821231319
P粉821231319

reply all(1)
P粉186017651

If you want to trigger some action when the option changes, then you can use a watcher to achieve this:

setup() {
    const options = [ ... ];

    const selectedOption = Vue.ref({ ... });

    Vue.watch(selectedOption, () => {
        // selectedOption 改变了
    });

    return {
        options,
        selectedOption
    };
}

If you want to customize VSelect, like you showed in the first example, then you can replace the options component. But I believe Vuetify already handles the active state, so there's no need to modify it unless you need a specific design.

<v-select v-model="selectedOption" :items="options" item-title="state" item-value="abbr" label="Select" return-object single-line>
    <template #item="{ item, props }">
        <v-list-item v-bind="{ ...props, title: undefined }">
            {{ item.value.abbr === selectedOption.abbr ? 'selected' : '' }} {{ item.title }}
        </v-list-item>
    </template>
</v-select>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template