【问题标题】:Using Rest Api how to load data in dropdown in Vuejs?使用 Rest Api 如何在 Vuejs 的下拉列表中加载数据?
【发布时间】:2021-10-08 05:04:26
【问题描述】:

new Vue({
    el: '#app',
    
    data: function() {
        return {
            countries: [],
            cities: [],
            selectedContinent: "",
            selectedCountry: "",
            selectedCity: ""
        }
    },
    watch: {
        selectedContinent: function() {
            // Clear previously selected values
            this.countries = [];
            this.cities = [];
            this.selectedCountry = "";
            this.selectedCity = "";
            // Populate list of countries in the second dropdown
            if (this.selectedContinent.length > 0) {
                this.countries = this.places[this.selectedContinent]
            }
        },
        selectedCountry: function() {
            // Clear previously selected values
            this.cities = [];
            this.selectedCity = "";
            // Now we have a continent and country. Populate list of cities in the third dropdown
            if (this.selectedCountry.length > 0) {
                this.cities = this.places[this.selectedContinent][this.selectedCountry]
            }
        }
    }
})
.dropdown {
    margin: 10px 0;
    padding: 10px 0;
    border-bottom: 1px solid #DDD;
}

.dropdown span {
    display:inline-block;
    width: 80px;
}
<body>
    <div id="app">
       <div class="cascading-dropdown">
            <div class="dropdown">
                <span>Continent:</span>
                <select v-model="selectedContinent">
                    <option value="">Select a Continent</option>
                    <option v-for="(country_obj, country) in places" :value="country">{{country}}</option>
                </select>
            </div>
            <div class="dropdown">
                <span>Country:</span>
                <select :disabled="countries.length == 0" v-model="selectedCountry">
                    <option value="">Select a Country</option>
                    <option v-for="(city_obj, city) in countries">{{city}}</option>
                </select>
            </div>
            <div class="dropdown"> 
                <span>City:</span>
                <select :disabled="cities.length == 0" v-model="selectedCity">
                    <option value="">Select a City</option>
                    <option v-for="city in cities">{{city}}</option>
                </select>
            </div>
        </div>
    </div> 
</body> 

以下是国家、州和城市的 REST API https://www.universal-tutorial.com/rest-apis/free-rest-api-for-country-state-city 我已经生成了一个令牌。 生成的令牌:IIPwMXygilaKrQJfNLuj-LHZWn5kxBVZRLJ-KtU5jxRivdTBkHio6IOyF60CERyOPjo

工作代码和框链接:- https://jsfiddle.net/Dhanunjay/sj24kn0b/6/

使用数据中的项目列表,我可以在下拉列表中加载数据。但我不确定如何在下拉列表中使用 rest api 加载数据

按照此文档了解适用于国家、州和城市的免费 REST API

【问题讨论】:

  • 这取决于你想如何使用它。如果你想在下拉列表中显示来自 API 响应的数据,那么你应该在挂载的生命周期钩子中进行 api 调用,并将 response.data 分配给 data 中的预定义项,并在模板中循环遍历它。不过,您可能需要格式化响应。如果您想在每次下拉更改时显示数据,请将其转换为函数并在每次选择新项目时调用它。
  • @uke5tar 我尝试了下面的代码jsfiddle.net/Dhanunjay/sj24kn0b/5 我在模板中循环了数据。但我不确定如何将响应分配给下拉列表。您能帮我了解如何在下拉列表中放置响应吗?
  • @uke5tar 正如你所说,我更新了我的代码。但是响应如何在下拉列表中加载不知道。
  • 你的意思是这样的:codesandbox.io/s/…

标签: javascript vue.js drop-down-menu axios


【解决方案1】:

第 1 步: 创建 HTML 您的模板

<template>
  <div class="cascading-dropdown">
    <div class="dropdown">
      <H2>Build a reusable dropdown vue component</H2>
      <span>Country:</span>
      <select v-model="selectedCountry" @change="onChangeCountry">
        <option value="">Select a Country</option>
        <option
          v-for="(country, index) in listCountry"
          :value="country.country_name"
          :key="index"
        >
          {{ country.country_name }}
        </option>
      </select>
    </div>
    <div class="dropdown">
      <span>State:</span>
      <select
        :disabled="listState.length == 0"
        v-model="selectedState"
        @change="onChangeState"
      >
        <option value="">Select a State</option>
        <option
          v-for="(state, index) in listState"
          :key="index"
          :value="state.state_name"
        >
          {{ state.state_name }}
        </option>
      </select>
    </div>
    <div class="dropdown">
      <span>State:</span>
      <select :disabled="listCities.length == 0" v-model="selectedCity">
        <option value="">Select a City</option>
        <option
          v-for="(city, index) in listCities"
          :key="index"
          :value="city.city_name"
        >
          {{ city.city_name }}
        </option>
      </select>
    </div>
    <p v-if="selectedCountry">Selected Country - {{ this.selectedCountry }}</p>
    <p v-if="selectedState">Selected State - {{ this.selectedState }}</p>
    <p v-if="selectedCity">Selected City - {{ this.selectedCity }}</p>
  </div>
</template>

第 2 步: 创建 model 数据

data() {
  return {
    listCountry: [],
    listState: [],
    listCities: [],
    selectedCountry: "",
    selectedState: "",
    selectedCity: "",
    authToken: "",
  };
},

第 3 步: 获取适用于国家、州和城市的免费 REST API。我们需要从api-token生成auth_token

generateAccessToken() {
  axios
    .get("https://www.universal-tutorial.com/api/getaccesstoken", {
      headers: {
        Accept: "application/json",
        "api-token":
          "jAJuES2nNREYu0qOJ9Sy6bydr_LPxmjv0jUAR-oEuXozRP_CjqPqRgp1mCPaNh8VPZo",
        "user-email": "itjebasuthan@gmail.com",
      },
    })
    .then((res) => {
      this.authToken = res.data.auth_token;
      this.loadCountry();
    });
},

第 4 步:为国家、州和城市创建 onChange 事件

loadCountry() {
  axios
    .get("https://www.universal-tutorial.com/api/countries", {
      headers: {
        Authorization: `Bearer ${this.authToken}`,
        Accept: "application/json",
      },
    })
    .then((res) => {
      this.listCountry = res.data;
    });
},
onChangeCountry() {
  axios
    .get(
      `https://www.universal-tutorial.com/api/states/${this.selectedCountry}`,
      {
        headers: {
          Authorization: `Bearer ${this.authToken}`,
          Accept: "application/json",
        },
      }
    )
    .then((res) => {
      this.listState = res.data;
    });
},
onChangeState() {
  axios
    .get(
      `https://www.universal-tutorial.com/api/cities/${this.selectedState}`,
      {
        headers: {
          Authorization: `Bearer ${this.authToken}`,
          Accept: "application/json",
        },
      }
    )
    .then((res) => {
      this.listCities = res.data;
    });
},

DEMO

【讨论】:

    猜你喜欢
    • 2021-04-10
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 2016-08-19
    • 2023-04-07
    • 2015-09-19
    • 2017-05-18
    • 1970-01-01
    相关资源
    最近更新 更多