使用 Vue 和 Axios 中的 API 数据填充选择标签

Waj*_*ouf 5 laravel vue.js

我想用来自 api get 请求的数据填充选择标签。这是我的 html 代码

<div id="app">
    <label for="country" class="control-label">Country</label>
    <select v-model="selectedCountry" @change="onChangeCountry" name="country" id="country" class="form-control" tabindex="11">
        <option selected disabled value="">Please select one</option>
        @foreach($countries as $country)
            <option value="{{ $country->id }}">{{ $country->name }}</option>
        @endforeach
    </select>
    <label for="city" class="control-label">City</label>
    <select v-model="cities" name="city" id="city" class="form-control" tabindex="12">
        <option v-bind:value="city.id">@{{ city.name }}</option>
    </select>
</div>
Run Code Online (Sandbox Code Playgroud)

现在我的 JavaScript 代码:

<script type="text/javascript">
    new Vue({
      el: '#app',
      data: {
        selectedCountry: '',
        cities: []
      },
      methods: {
          onChangeCountry: function (event) {
            axios.get('http://localhost:8000/api/cities/country/' + this.selectedCountry)
            .then(function (
                this.cities = response.data
            }).catch(function(error) {
                console.log('an error occured ' + error);
            });
          }
        }
    });
</script>
Run Code Online (Sandbox Code Playgroud)

我很确定收到了数据,因为我做了很多 console.log,但我不知道如何将收到的数据附加到我的第二个选择标签,也不知道如何继续。

Sér*_*eis 5

在选择中尝试这个

<select v-model="selectedCity" name="city" id="city" class="form-control" tabindex="12">

   <option v-for="(city,cityIndex) in cities" :key="city.id" :value="city.id">{{ city.name }}</option>

</select>
Run Code Online (Sandbox Code Playgroud)

将 'selectedCity' 添加到数据对象中,然后通过 this.selectedCity 访问其值

这是 vue 文档中的

https://v2.vuejs.org/v2/guide/list.html

https://v2.vuejs.org/v2/guide/forms.html#Select


Waj*_*ouf 2

我终于让它工作了,
我只需要在数据函数中创建一个城市变量
,在选择中我不需要将它绑定到城市数组[],城市变量很好v-model="city"