我有来自后端的国家和城市jsons。当我选择城市中的一个国家选择拥有该国家的城市时,我想在vuejs中进行制作。
我被困在这里,我不知道如何仅为所选国家带来城市。
有人可以给我一点帮助吗?
国家/地区JSON
GET / languages / countries(国家/地区列表)
{
"errorCode": 0,
"errorMessage": null,
"contries": [
{
"errorCode": 0,
"errorMessage": null,
"rid": "1",
"sortname": "AF",
"name": "Afghanistan",
"phonecode": 93,
"links": []
},
{
"errorCode": 0,
"errorMessage": null,
"rid": "2",
"sortname": "AL",
"name": "Albania",
"phonecode": 355,
"links": []
},
{
"errorCode": 0,
"errorMessage": null,
"rid": "3",
"sortname": "DZ",
"name": "Algeria",
"phonecode": 213,
"links": []
}
],
"links": []
}
城市JSON
GET / languages / countries / 1(id = 1的国家/地区列表)
{
"errorCode": 0,
"errorMessage": null,
"cities": [
{
"errorCode": 0,
"errorMessage": null,
"rid": "33129",
"name": "Abrud",
"stateId": 2934,
"links": []
},
{
"errorCode": 0,
"errorMessage": null,
"rid": "33130",
"name": "Aiud",
"stateId": 2934,
"links": []
},
{
"errorCode": 0,
"errorMessage": null,
"rid": "33131",
"name": "Alba Iulia",
"stateId": 2934,
"links": []
}
],
"links": []
}
VueJS脚本
export default {
data() {
return {
users: {},
countries: {},
cities: {}
}
},
created() {
this.getUsers();
this.getCountries();
this.getCities();
},
methods: {
getUsers() {
this.$http.get("/user")
.then((response) => {
this.users = response.data.users;
})
},
getCountries() {
this.$http.get("/languages/countries")
.then((response) => {
this.countries = response.data.contries;
})
},
getCities() {
this.$http.get("/languages/countries/"+this.country.rid)
.then((response) => {
this.cities = response.data.cities;
})
},
},
components: {
appMenu: Menu
}
}
HTML选择
<div class="form-group">
<div class="row">
<div class="col-6 pz-rel">
<label class="eda-form-label" for="country">COUNTRY</label>
<select class="eda-form-input">
<option v-for="country in countries" :value="country.name">{{country.name}}</option>
</select>
<i class="ti-angle-down icons-for-select"></i>
</div>
<div class="col-6 pz-rel">
<label class="eda-form-label" for="city">CITY</label>
<select class="eda-form-input">
<option v-for="city in cities" :value="city.name">{{city.name}}</option>
</select>
<i class="ti-angle-down icons-for-select"></i>
</div>
</div>
</div>
答案 0 :(得分:2)
因此,在第一步中,您将获得所有国家/地区 然而,如果您所描述的城市有其余的电话,则无法同时获得所有国家/地区的所有城市 因此,我将获取当前所选国家/地区的城市
修改强>
必须更改<option>
行。目前,该值将绑定到name
。所以必须从< ... :value="country.name" to :value="country">
<select class="eda-form-input" v-model='selectedCountry' v-on:change='getCities(selectedCountry.rid)'>
<option v-for="country in countries" :value="country"> <!-- here -->
{{country.name}}
</option>
</select>
上面还有一个数据变量selectedCountry
,它将保留当前选定的国家/地区。所以这也必须在data
中声明。
data() {
return {
users: {},
countries: {},
cities: {},
selectedCountry: null
}
},
并为getCities方法提供该国家/地区的参数:
getCities(countryId) {
this.$http.get("/languages/countries/"+countryId)
.then((response) => {
this.cities = response.data.cities;
})
},