You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue 3中如何为动态组件传递自定义Props并实现逐题展示

实现单题切换的Vue动态组件方案

核心思路

不需要创建多个QuestionCard组件实例,只需维护一个当前题目的索引,动态给同一个QuestionCard组件传递不同题目数据即可,配合动态组件实现切换效果(本质是固定组件类型,动态更新props)。

具体修改步骤

1. 更新App.vue的data数据

添加索引变量跟踪当前题目位置,同时指定固定使用的组件:

<script lang="ts">
import { defineComponent } from 'vue';
import QuestionCard from "./components/QuestionCard.vue";

export default defineComponent({
  components: {
    QuestionCard
  },
  data() {
    return {
      questionArray: [
        {
          id: "123",
          question: "Which of these is a colour in the rainbow?",
          options: ['red', 'black', 'brown'],
        }, {
          id: "456",
          question: "How many continents does Earth have?",
          options: [1, 7, 6, 9],
        }, {
          id: "789",
          question: "Which of these is a prime number?",
          options: [7, 4, 44, 35],
        },
      ],
      currentQuestionIndex: 0, // 当前显示的题目下标,初始为第1题
      currentComponent: QuestionCard // 固定绑定QuestionCard组件
    }
  },
  methods: {
    nextQuestion() {
      // 边界判断:未到最后一题时才切换
      if (this.currentQuestionIndex < this.questionArray.length - 1) {
        this.currentQuestionIndex++
      }
    }
  }
})
</script>

2. 修改模板,动态传递props并绑定切换事件

更新组件的props绑定,同时给按钮添加点击事件和禁用逻辑:

<template>
  <div>
    <div id="top_bar">
      <!-- 可选:添加题目进度显示 -->
      <span>{{ currentQuestionIndex + 1 }} / {{ questionArray.length }}</span>
      <button 
        @click="nextQuestion"
        :disabled="currentQuestionIndex >= questionArray.length - 1"
      >
        Next Question
      </button>
    </div>

    <div id="question_section">
      <component 
        :is="currentComponent"
        :question="questionArray[currentQuestionIndex].question"
        :answer_options="questionArray[currentQuestionIndex].options"
      ></component>
    </div>
  </div>
</template>

方案说明

这里的动态组件只是用来指定固定的QuestionCard类型,核心是通过currentQuestionIndex的变化,动态更新传递给组件的question和answer_options props,从而实现单题切换的效果。这种方式比创建多个组件实例更高效,避免了不必要的组件销毁与重建。

内容的提问来源于stack exchange,提问作者sweet-pineapple

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 20:33:39