"我希望对我从JSON文件中获取的测验问题和答案进行分类. 在VUE模板中.我try 了v-for指令,但我不能使用模板中的Object键. 为了更清楚地说明,我将在脚本部分演示到目前为止我所做的工作. 希望拥有与此类似的东西: 1-第一个问题

  • A/第一个答案
  • B/发送应答 ……

这是VUE文件

<template>
  <div class="lg:pl-64 flex flex-col">

    <div v-for="data in datas">
      <h1>{{ data.question }}</h1>
    </div>
    <div>
      // looking to add multiple choice answers in here
    </div>

  </div>
</template>
<script setup>
import myData from "../data/data.json"
const datas = myData
const answers = []


datas.forEach((element) => {
  // pushing all the answers from JSON file to the answers array
  answers.push(element.answers)
})

// looping throught the arrays of objects to bring the key and value
answers.forEach((answer) => {
  for (let i = 0; i < answer.length; i++) {
    for (const key in answer[i]) {
      console.log(`${key}: ${answer[i][key]}`)
    }
  }
})
</script>

这是data.JSON文件

[
  {
    "id": 1,
    "question": "first Question",
    "answers": [{
        "a" : "first answer1",
        "b" : "second answer1",
        "c" : "third answer1",
        "z" : "fourth answer1"
    }],
    "correct": "a"
  }
,
    {
      "id": 2,
      "question": "second Question",
      "answers": [{
          "a" : "first answer2",
          "b" : "second answer2",
          "c" : "third answer2",
          "z" : "fourth answer2"
      }],
      "correct": "a"
    }
]

推荐答案

要显示每个多项 Select 题的答案选项,您可以更改模板,使其包含另一个v-for指令,如下所示:

<template>
  <div class="lg:pl-64 flex flex-col">
    <div v-for="data in datas" :key="data.id">
      <h1>{{ data.id }} - {{ data.question }}</h1>
      <ul>
        <li v-for="(answer, index) in data.answers[0]" :key="index">
          {{ index }} / {{ answer }}
        </li>
      </ul>
    </div>
  </div>
</template>

您的其余代码看起来是正确的.希望这能有所帮助!

Vue.js相关问答推荐

vue : 多个样式的类绑定在一个

VeeValidate 4 字段验证状态

使用 Vue.js 清除数组内容和react性问题

拖入 vue2-google-map 后如何获取标记位置?

如何对将 DOM 元素附加到 HTML 正文的 Vue 组件进行单元测试?

PhpStorm 中Expected预期表达式

Transition-group children must be keyed...but they are keyed

如何使用 vuex 删除项目?

使用vue.js单击时如何获取按钮的值

将 Vuetify 从 1.5 升级到 2 时,Sass-loader 错误 'options has an unknown property 'indentedSyntax''

将 VueJS 数据属性重置为初始值

Vuetify Jest 未知自定义元素

如何使用 JavaScript 按索引删除数组元素?

vue 3 使用 Vuex 和路由的服务器端渲染

使用 Vue.js & DataTable(jquery 插件)

Laravel 和 Vue - handler.call 不是函数

无法访问函数内的数据属性

更改事件上的 Select2 在 Vuejs 中不起作用

使用 VueJS 使用 3rd 方库打印元素

Vue.js 显示空格(换行符)