当然可以帮您使用Vue3编写一个包含多选、单选、填空和简答题的问卷调查页面。
首先,您要确保您已经安装了Vue3的开发环境。可以通过下面的命令来检查您的Vue版本:
code
vue --version
如果您没有安装Vue CLI,请使用以下命令全局安装Vue CLI:
code
npm install -g @vue/cli
接下来,您可以通过以下命令创建一个新的Vue项目:
code
vue create questionnaire
然后选择Default (Vue 3 Preview),并且等待项目创建完毕。
进入到项目文件夹中:
code
cd questionnaire
现在,您可以使用您喜欢的代码编辑器打开项目。
我们可以开始编写问卷调查页面的代码。
首先,创建一个用于展示问题的组件 Question.vue,并且在其中编写以下代码:
vue
<template>
<div>
<h3>{{ question }}</h3>
<template v-if="type === 'single'">
<ul>
<li v-for="option in options" :key="option">
<label>
<input type="radio" :name="id" :value="option" v-model="answer" />
{{ option }}
</label>
</li>
</ul>
</template>
<template v-else-if="type === 'multiple'">
<ul>
<li v-for="option in options" :key="option">
<label>
<input type="checkbox" :name="id" :value="option" v-model="answers" />
{{ option }}
</label>
</li>
</ul>
</template>
<template v-else-if="type === 'text'">
<textarea v-model="answer" rows="4" cols="50"></textarea>
</template>
<template v-else-if="type === 'essay'">
<textarea v-model="answer" rows="6" cols="50"></textarea>
</template>
<button @click="submit">提交</button>
</div>
</template>
<script>
export default {
props: {
id: String,
type: String,
question: String,
options: Array
},
data() {
return {
answer: '',
answers: []
};
},
methods: {
submit() {
if (this.type === 'text' || this.type === 'essay') {
if (this.answer === '') {
alert('请填写答案');
return;
}
}
if (this.type === 'multiple') {
if (this.answers.length === 0) {
alert('请至少选择一个选项');
return;
}
}
// 执行提交逻辑,可以将问题id和用户答案发送到后端或其他处理方式
console.log('问题ID:', this.id);
console.log('用户答案:', this.type === 'multiple' ? this.answers : this.answer);
}
}
};
</script>
这里我们根据题目的不同类型,分别使用单选框、多选框、文本框和文本域来展示问题,并且通过 v-if 和 v-else-if 来根据不同题目类型显示不同的内容。然后使用 v-model 为每个输入控件绑定数据。
接下来,我们需要在主页 App.vue 中使用这个组件。在 App.vue 的模板中编写以下代码:
vue
<template>
<div id="app">
<h1>问卷调查</h1>
<Question
v-for="question in questions"
:key="question.id"
:id="question.id"
:type="question.type"
:question="question.question"
:options="question.options"
/>
</div>
</template>
<script>
import Question from './components/Question.vue';
export default {
components: {
Question
},
data() {
return {
questions: [
{
id: '1',
type: 'single',
question: '你最喜欢的颜色是?',
options: ['红色', '蓝色', '绿色', '黄色']
},
{
id: '2',
type: 'multiple',
question: '你喜欢的水果是什么?',
options: ['苹果', '香蕉', '橙子', '草莓']
},
{
id: '3',
type: 'text',
question: '请问你的名字是?'
},
{
id: '4',
type: 'essay',
question: '请问你对此问卷调查有什么建议或意见?'
}
]
};
}
};
</script>
在这个示例中,我们向 App.vue 中添加了一个问题数组,每个问题对象包含问题的ID、类型(single, multiple, text, essay)、问题内容和选项(仅用于单选和多选问题)。然后我们使用 v-for 循环将每个问题渲染成 Question 组件。
最后,我们需要修改 main.js 来启动我们的应用。在文件中写入以下内容:
javascript
import { createApp } from 'vue';
import App from './App.vue';
createApp(App).mount('#app');
现在,您可以通过以下命令来启动应用程序:
code
npm run serve
在浏览器中访问 http://localhost:8080,您将看到一个问卷调查页面,其中包含了多选、单选、填空和简答题。当用户点击 提交 按钮时,将在控制台中打印出用户的答案或进行相应的处理。
这只是一个简单的示例,您可以根据具体需求进一步扩展和改进此页面。希望对您有帮助!如果您有其他问题,请随时提问。