【发布时间】:2020-08-11 16:22:28
【问题描述】:
我已经尝试了各种方法来将我的 API 数据提取到选择列表中。然而,我失败了。所有的信息都成功了。但是,每当我尝试向他们展示时,它都行不通。我的代码有问题吗?
我的路由/web.php 文件
<?php
Route::get('/','StatusController@index');
我的控制器
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class StatusController extends Controller
{
//
public function index(){
return view('status-main');
}
}
我的 VueJS 文件
<template>
<div class="container">
<h2>Total Recovered: {{Recovered}}</h2>
<select name="" id="" >
<option value="">Choose</option>
<option v-for="(list,index) in countryList" :key="list.id" :index="index">
{{list}}
</option>
</select>
</div>
</template>
<script>
import axios from 'axios'
export default {
name:'CoronaStatus',
data: function () {
return {
Recovered: "Loading ...",
countryList:[],
// Country:''
}
},
// mounted(){
//
// this.globalStatus();
// },
methods:{
globalStatus:function () {
const options = {
headers: {"x-rapidapi-host": "covid-193.p.rapidapi.com",
"x-rapidapi-key": "ad21211fe4mshba485cda44108adp1712e0jsn54ed45914a9a"}
};
axios
.get("https://covid-193.p.rapidapi.com/countries", options)
.then(response=>response.json())
.then(response => {
// this.Recovered = response.data.Global.TotalRecovered;
this.countryList=response.data;
console.log(this.countryList);
// alert(this.countryList)
})
.catch(err => console.log(err));
}
},
mounted(){
this.globalStatus();
},
}
</script>
<style scoped>
</style>
我每次都成功获取数据。但是,我未能填充选择列表。
更新后我的 VueJS 文件:
<template>
<div class="container">
<select name="country">
<option disabled value="">Choose</option>
<option v-for="country in countryList" :key="country" :value="country">
{{ country }}
</option>
</select>
</div>
</template>
<script>
import axios from 'axios'
export default {
data: () => ({
Recovered: "Loading ...",
countryList: []
}),
methods: {
globalStatus () {
const options = {
headers: {
"x-rapidapi-host": "covid-193.p.rapidapi.com",
"x-rapidapi-key": "ad21211fe4mshba485cda44108adp1712e0jsn54ed45914a9a"
}
}
axios.get('https://covid-193.p.rapidapi.com/countries', options).then(res => {
this.countryList = res.data.response
console.log(this.countryList);
})
}
},
mounted () {
this.globalStatus()
}
}
</script>
<style scoped>
</style>
【问题讨论】:
-
你能提供一个国家列表数据的小例子吗?
-
我建议你好好阅读 Vue 指南中的这一部分~vuejs.org/v2/guide/forms.html#Select。特别是 “使用
v-for呈现的动态选项” 部分 -
你使用的是Axios,不是
fetch,所以你不需要使用response.json()。您肯定会在开发者控制台中报告错误