Vue Select Depend on each other

by Roland Doda

HTML

<div id="app">
  <select v-model="selectedState" @change="stateChanged">
    <option :value="null">Select State</option>
    <option
      v-for="state in states"
      :key="state.id"
     :value="state.id"
     >
       {{state.text}}
     </option>
  </select>
    
  <select v-model="selectedCity">
    <option :value="null">Select City</option>
    <option
      v-for="city in citiesDependOnSelectedState"
      :key="city.id"
      :value="city.id"
     >
       {{city.text}}
     </option>
  </select>
</div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

Vue

new Vue({
  el: "#app",
  data: {
    states: [
      { text: "Albania", id: 1 },
      { text: "Greece", id: 2 },
      { text: "Italy", id: 3 },
      { text: "Germany", id: 4 }
    ],
    cities: [
    	{ text: "Tirana", id: 1, state: 1 },
      { text: "Vlora", id: 2, state: 1 },
      { text: "Thessaloniki", id: 3, state: 2 },
      { text: "Athens", id: 4, state: 2 },
      { text: "Berlin", id: 5, state: 4 },
      { text: "Hamburg", id: 6, state: 4 },
      { text: "Rome", id: 7, state: 3 },
      { text: "Milano", id: 8, state: 3 }
    ],
    selectedState: null,
    selectedCity: null
  },
  computed: {
    citiesDependOnSelectedState() {
    	return this.cities.filter(el => el.state === this.selectedState)
    }
  },
  methods: {
  	stateChanged() {
    	this.selectedCity = null
    }
  }
})