0

Есть компонент в котором создаются два поля select(country, city) по клику. Поля зависимые, при выборе страны изменяются значения во втором селекте (города). Проблема заключается в том, что когда мы изменяем один select(страна) изменяются все другие select-ы (города).

 <template>

<b-container class="bv-example-row">

  <b-row v-for="(station, counter) in stations" v-bind:key="counter">
    <b-col cols="6">
      <label>Страна</label>
      <select class='form-control' name="country_dest_id" v-model='station.country' @change='getStates($event)'>
        <option value='0' >Select Country</option>
        <option v-for='data in countries' :value='data.id'>{{ data.name }}</option>
      </select>
    </b-col>

    <b-col cols="6">
      <label >Город</label>
      <select class='form-control' v-model='station.state'>
        <option value='0' >Select State</option>
        <option v-for='data in states' :value='data.id'>{{ data.name }}</option>
      </select>
    </b-col>

   

    <b-col cols="1">
      <button class="btn btn-danger remove" @click="deleteStation(counter)"><i class="fa fa-times" aria-hidden="true"></i> Удалить</button>
    </b-col>
  </b-row>

  <b-row class="justify-content-md-center">
    <b-col cols="3" md="3">
      <button class="btn btn-success" type="button" @click="addStation">Добавить</button>
    </b-col>
  </b-row>
</b-container>
</template>
<script>

export default {
  mounted() {
    console.log('Component mounted.')
  },

  data(){
    return {
      stations:[
        {
          country: '',
          state:'',
        }
      ],
      countries: [],
      states:[]
    }
  },

  methods:{
    addStation(){
      this.stations.push({
        country:'',
        state: ''
      })
    },

    deleteStation(counter){
      this.stations.splice(counter,1);
    },

    getCountries: function(){
      axios.get('/getCountries')
          .then(function (response) {
            this.countries = response.data;
          }.bind(this));
    },


    getStates: function(event) {
      console.log(event.target.value);
      axios.get('/getStates',{
        params: {
          country_id: event.target.value
        }
      }).then(function(response){
        this.states = response.data;
      }.bind(this));

    }

  },

  created: function(){
    this.getCountries()
  }


}
</script>

введите сюда описание изображения

1 ответ 1

0

Проблема в одинаковых v-model, которые, когда создаете новый селект, ссылаються на одну и туже переменую, как вариант можно сделать масив обьектов из переменных, чтоб динамически по индексу добавлять туда и связывать с select через v-model тогда в каждом select будет своя переменная куда вносить свое значение

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.