Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

javascript - x-for is not working reactively in alpinejs

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
        });
      }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...