在Vue 2.1中使用另一个下拉列表动态更新一个下拉列表

时间:2017-03-17 15:41:30

标签: javascript jquery vue.js

我有一个在Vue v.2中构建的带有地址部分的表单。我试图根据在城市中选择的内容将州下拉列表自动填充。当用户选择“亚特兰大”时,“格鲁吉亚”应显示在状态下拉列表中。这看起来应该很简单,特别是因为我使用的是jQuery。我试图实现能够注销正确状态的this solution,但下拉列表仍会显示“* State”。我必须在这里错过一些简单的东西。

 <div class="grid-33 city">
   <select name="business-address-city"
           v-model="bi.addresses.business.city"
           @change="updateCityState(bi.addresses.business.city)>
     <option value="">*City</option>
     <option value="Atlanta">Atlanta</option>
     <option value="Houston">Houston</option>
     <option value="Los Angeles">Los Angeles</option>
     <option value="Miami">Miami</option>
     <option value="Minneapolis">Minneapolis</option>
   </select>
 </div>

 <div class="grid-33 state">
   <select name="business-address-state" v-model="bi.addresses.business.state">
     <option value="">*State</option>
     <option value="California">California</option>
     <option value="Florida">Florida</option>
     <option value="Georgia">Georgia</option>
     <option value="Minnesota">Minnesota</option>
     <option value="Texas">Texas</option>
   </select>
 </div>


data () {
  return {
    bi: businessInfo,
    checked: true
  }
},
watch: {
  bi.addresses.business.city: function () {
    if ($('[name="business-address-city"]').val() == 'Atlanta') {
      $('[name="business-address-state"]').val('Georgia').change()
    }
  }
},
methods: {
  updateCityState (e) {
    var city = e
    var state = $('[name="business-address-state"]')
    console.log(state);
    switch (city) {
      case 'Atlanta':
        $('[name="business-address-state"] options').val('Georgia').change()
        break
      case 'Houston':
        state = 'Texas'
        break
      case 'Los Angeles':
        state = 'California'
        break
      case 'Miami':
        state = 'Florida'
        break
      case 'Minneapolis':
        state = 'Minnesota'
        break
    }
  }
}

1 个答案:

答案 0 :(得分:1)

我可以建议一种不同的方法吗?通常,使用Vue,除非您专门使用jQuery插件,否则根本不需要jQuery。

如果您在同一州有多个城市,则需要对其进行修改,但希望您能在此处看到这个想法。如果可能的话,你想要一个状态下拉似乎很奇怪。

const locations = [
  {
    city: "Atlanta",
    state: "Georgia"
  },
  {
    city:"Houston",
    state:"Texas"
  },
  {
    city: "Los Angeles",
    state: "California"
  },
  {
    city: "Miami",
    state: "Florida"
  },
  {
    city:"Minneapolis",
    state:"Minnesota"
  }
]

new Vue({
  el:"#app",
  data:{
    locations,
    bi: businessInfo,
    selectedLocation: null
  },
  watch:{
    selectedLocation(){
      this.bi.address.business.city = this.selectedLocation.city;
      this.bi.address.business.state = this.selectedLocation.state;
    }
  }
})

您的模板变为

<div id="app">
  <select v-model="selectedLocation">
    <option v-for="location in locations" :value="location">{{location.city}}</option>
  </select>
  <select v-model="selectedLocation">
    <option v-for="location in locations" :value="location">{{location.state}}</option>
  </select>
</div>

Example