[英]Populating options for select using v-for VueJS after handling load data event
I have this VueJS application written using Typescript.我有这个使用 Typescript 编写的VueJS应用程序。 I'm using Axios to get data from my database.
我正在使用Axios从我的数据库中获取数据。 This works well and the result I get is an array which is what I was expecting.
这很有效,我得到的结果是一个数组,这正是我所期望的。 When I do
console.log
on this array I can see that it's the correct result.当我在这个数组上执行
console.log
,我可以看到它是正确的结果。
However, when I try to loop through this array to create the options for my select drop down I get a blank list.但是,当我尝试遍历这个数组来为我的选择下拉列表创建选项时,我得到一个空白列表。 Why isn't the result coming up even though the variable I'm looping through is an array?
为什么即使我循环的变量是一个数组,结果也没有出现?
Edit: I've added a picture here showing the Axios result ( response.data
)编辑:我在这里添加了一张图片来显示 Axios 结果(
response.data
)
export default class EditRoute extends Vue {
result: any;
selectedRoute: string;
constructor(){
super();
this.selectedRoute = "";
this.result = [];
}
loadData() {
axios.get('http://localhost:8080/routes')
.then(response => (this.result = response.data));
}
}
<select name="routeSelect" v-model="selectedRoute">
<option v-for="routes in result" v-bind:key="routes.name" v-bind:value="routes.name"> {{ routes.name }} </option>
</select>
<button @click="loadData">Load data</button>
Since your result
is an object which is containing one item, that item is an array called routes
in this case you should loop through result.routes
like so :由于您的
result
是一个包含一个项目的对象,因此该项目是一个名为routes
的数组,在这种情况下,您应该像这样循环遍历result.routes
:
<option v-for="routes in result.routes" v-bind:key="routes.name" v-bind:value="routes.name"> {{ routes.name }} </option>
Extra Example :额外示例:
new Vue({ el: '#app', data: function() { return { selectedUser: '', users: [], } }, mounted: function() { // this.loadData(); // this.timer = setInterval(this.loadData, 4000); }, methods: { loadData: function() { axios.get('https://jsonplaceholder.typicode.com/users').then(response => { this.users = response.data; }).catch(e => { }) } } })
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <script src="https://unpkg.com/vue@2.5.17/dist/vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script src="https://unpkg.com/vue-axios@2.1.4/dist/vue-axios.min.js"></script> </head> <body> <div id="app"> <select name="userSelect" v-model="selectedUser"> <option v-for="user in users" v-bind:key="user.id" v-bind:value="user.name"> {{ user.name }} </option> </select> <button @click="loadData">Load data</button> </div> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.