简体   繁体   English

如何在 Vue.js 中从 JSON 数据创建选择元素?

[英]How create a select element from JSON data in Vue.js?

I want to render a JSON into a select input with Vue.js, but I don't know how because the JSON is a bit complicated.我想使用 Vue.js 将 JSON 渲染到选择输入中,但我不知道如何,因为 JSON 有点复杂。

The JSON is: JSON是:

{ 
   "08:00:00":"08:00:00 AM",
   "08:30:00":"08:30:00 AM",
   "09:00:00":"09:00:00 AM",
   "09:30:00":"09:30:00 AM",
   "10:00:00":"10:00:00 AM",
   "10:30:00":"10:30:00 AM",
   "11:00:00":"11:00:00 AM",
   "11:30:00":"11:30:00 AM"
}

As you can see, the JSON doesn't have a key to access into each element.如您所见,JSON 没有访问每个元素的密钥。 This is the reason why I cannot render with the typical way.这就是我不能用典型方式渲染的原因。 I'm implementing Vue.js in Laravel.我在 Laravel 中实现 Vue.js。

Make sure you have in your data() or computed part, the parsed JSON object.确保在data()computed部分中有解析的 JSON 对象。 Then you do something like:然后你做类似的事情:

<template>
    <select>
      <option v-for="(value, key) in yourParsedJsonObject" :value="key">{{value}}</option>
    </select>
</template>

<script>
export default {
    data(){
        return {
           yourParsedJsonObject: JSON.parse(...yourjson...)
        }
    }
}
</script

You can use the optional index as second argument -syntax of the v-for directive:您可以使用可选索引作为v-for指令的第二个参数 - 语法:

<li v-for="(row, index) in json">
  {{ index }}: {{ row }}
</li>

Full source code: https://vuep.run/7d8683b3完整源代码: https ://vuep.run/7d8683b3

Here an example with using select option elements:这是使用选择选项元素的示例:

<select v-model="selected">
  <option v-for="(row, index) in json">
    {{ index }}: {{ row }}
  </option>
</select>

Full source code: https://vuep.run/392a82b2完整源代码: https ://vuep.run/392a82b2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM