I'm trying to loop over an array of objects (i.e, carriageOptions array) using x-for. If I pre-populate it with some dummy values, it prints them as expected. But If I push an item dynamically to the carriageOptions array from axios response, x-for doesn't loop over reactively to the newly pushed items.
Blade
<div x-data="transportation()" x-init="initWatcher" x-ref="transportation">
<div class="form-group row">
<label class="col-md-3 col-form-label">Transits</label>
<div class="col-md-9 col-form-label">
@foreach ($transits as $transit)
<div class="form-check form-check-inline mr-1">
<input class="form-check-input" id="{{ $transit->id }}" name="transit{{ $transit->id }}" type="checkbox" value="{{ $transit->id }}" x-model="checkedTransits">
<label class="form-check-label" for="{{ $transit->id }}">{{ $transit->name }}</label>
</div>
@endforeach
</div>
</div>
<div class="form-group row">
<label class="col-md-3 col-form-label" for="carriage_id">Carriage</label>
<div class="col-md-9">
<select class="form-control" id="carriage_id" name="carriage_id" autocomplete="off">
<template x-for="carriageOption in carriageOptions" :key="carriageOption">
<option x-bind:value="carriageOption.id" x-text="carriageOption.name"></option> --> this is printing nothing ....
</template>
</select>
</div>
</div>
</div>
JS
function transportation() {
return {
checkedTransits: [],
carriageOptions: [],
initWatcher() {
this.$watch("checkedTransits", function(value) {
var carriageOptions = [];
value.forEach(async function (element) {
const response = await axios.get(`/transits/${element}?ajax=1`);
carriageOptions.push({name: response.data.name, id: response.data.id});
});
this.carriageOptions = carriageOptions;
console.log(this.carriageOptions); --> I'm getting expected values here
});
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…