uniapp + node.js 开发问卷调查小程序

前后端效果图
在这里插入图片描述
后端:nodejs 12.8 ; mongoDB 4.0
前端:uniapp
开发工具:HBuilderX 3.99

  • 前端首页代码 index.vue
<!-- 源码下载地址  https://pan.baidu.com/s/1AVB71AjEX06wpc4wbcV_tQ?pwd=l9zp --><template><view class="container"><view class="content"><view class="question" v-for="(item,index) in qusetionList" :key='index'><view class="question_header"><view class="header_title">{{item.subjectContent}}<text style="font-weight: 500;">({{item.type==0?'单选':'多选'}})</text></view></view><view class="question_option"><view :class="{option_item:true,active_option:items.id==items.active}"v-for="(items,indexs) in item.optionList" :key='indexs' @tap.stop="optionItem(items)"><view class="option_box"><image src="@/static/hook.png" mode=""></image></view><text>{{items.optionContent}}</text></view></view></view><view style="height: 180rpx;"><!-- 占位框,避免内容被提交按键遮挡 --></view></view><!-- 底部提交按键,@tap.stop阻止冒泡事件 --><view class="submit_box" @longpress="goAdmin"><button class="sub_btn" type="default" @tap.stop="subQuestion">提交</button></view></view>
</template><script>export default {data() {return {baseUrl:'',active: 0,qusetionList: [],}},onLoad() {// 获取全局变量 baseUrlthis.baseUrl = getApp().globalData.baseUrl;// 调用方法this.getData()},methods: {//获取用户信息getUserInfo(param) {},//获取题目、选项getData() {uni.request({url: this.baseUrl + 'query',method: "GET",data: {},success: (res) => {var arr =res.data.dataArrvar dataList = arr.sort(this.compare('sort')) //按对象内的sort字段进行排序数组// 每个问卷都加上状态字段activefor (let i in dataList) {var optionList = []for (let j in dataList[i].optionList) {dataList[i].optionList[j].active = ''optionList.push(dataList[i].optionList[j])}dataList[i].optionList = optionList}this.qusetionList = dataList},fail: () => {uni.showToast({title: "网络请求失败!",icon: 'none',duration: 2000})}})},//--- 数组内的对象按某个字段进行排序 ---//compare(property){return function(a,b){var value1 = a[property];var value2 = b[property];return value1 - value2;  //升序,  降序为value2 - value1}},// 选择及未选择样式切换optionItem(param) {// 根据每个字段的id作为唯一状态标识是否选中this.active = param.idfor (var i in this.qusetionList) {// 单项选择if (this.qusetionList[i].type == 0) {if (this.qusetionList[i].groudId == param.subjectId) {for (var j in this.qusetionList[i].optionList) {if (this.qusetionList[i].optionList[j].id == param.id && this.qusetionList[i].optionList[j].active =='') {this.qusetionList[i].optionList[j].active = param.id} else {this.qusetionList[i].optionList[j].active = ''}}}// 多项选择} else if (this.qusetionList[i].type == 1) {for (var j in this.qusetionList[i].optionList) {if (this.qusetionList[i].optionList[j].id == param.id) {if (this.qusetionList[i].optionList[j].active == '') {this.qusetionList[i].optionList[j].active = param.id} else if (this.qusetionList[i].optionList[j].active != '') {this.qusetionList[i].optionList[j].active = ''}}}}}},// 提交问卷subQuestion() {var subTime = Date.now()var userName = '名字' + subTime.toString ().slice(-3)var activeQuestion = [] //已选择的数据列表// 循环判断active是否为空,单选和多选因为传参格式需要区分判断for (var i in this.qusetionList) {// 单选判断循环if (this.qusetionList[i].type == 0) {for (var j in this.qusetionList[i].optionList) {if (this.qusetionList[i].optionList[j].active != '') {// 把已选择的数据追加到列表activeQuestion.push({subTime:subTime,userName: userName,// groudId: this.qusetionList[i].groudId,sort: this.qusetionList[i].sort,subjectContent: this.qusetionList[i].subjectContent,optionContent: this.qusetionList[i].optionList[j].optionContent})}}} else {// 多选判断循环,选项ID以逗号拼接成字符串var optionArr = []for (var j in this.qusetionList[i].optionList) {if (this.qusetionList[i].optionList[j].active != '') {// optionArr.push(this.qusetionList[i].optionList[j].id)optionArr.push(this.qusetionList[i].optionList[j].optionContent)}}// 把已选择的数据追加到列表if (optionArr != '') {activeQuestion.push({subTime:subTime,userName: userName,// groudId: this.qusetionList[i].groudId,sort: this.qusetionList[i].sort,subjectContent: this.qusetionList[i].subjectContent,//optionId: optionArr.join()optionContent:optionArr.join()})}}}//console.log(activeQuestion)if(activeQuestion.length < this.qusetionList.length){uni.showToast({title: "问题还没有回答完!",icon: 'none',duration: 2000});} else {//提交数据给后端uni.request({url: this.baseUrl + 'addAnswer',method: 'POST',header: {'content-type' : "application/x-www-form-urlencoded"},data: {formData: JSON.stringify(activeQuestion) //转换为JSON格式字符串},success: (res) => {// 服务器返回数据,后续业务逻辑处理console.log(res)// 调用方法,刷新数据this.getData()uni.showToast({title: "保存成功", icon : "success",duration:3000})},fail: (err) => {console.log(err)uni.showToast({ title: "服务器响应失败,请稍后再试!", icon : "none",})},complete: () => {}})}},// 跳转到页面goAdmin() {uni.navigateTo({url: '../admin/admin'})}}}
</script><style lang="less" scoped>.question {.question_header {// height: 90rpx;固定高度之后,长内容换行不能自动增加高度background-color: #f1f1f1;font-size: 34rpx;font-weight: 700;color: #333333;.header_title {width: 95%;margin-left: 37rpx;line-height: 90rpx;}}.question_option {width: 650rpx;margin-top: 7rpx;// background-color: #F0AD4E;display: flex;justify-content: space-between;flex-wrap: wrap;margin: 0 auto;margin-bottom: 40rpx;.option_item {width: 300rpx;margin-top: 34rpx;// background-color: #DD524D;font-size: 30rpx;color: #666666;display: flex;align-items: center;.option_box {width: 35rpx;height: 35rpx;border: 1rpx solid #999999;border-radius: 5px;margin-right: 10rpx;// background-color: #FF852A;display: flex;justify-content: center;align-items: center;image {width: 20rpx;height: 20rpx;}}}}}.active_option {.option_box {background: linear-gradient(-30deg, #ff7029 0%, #faa307 100%);border: 1rpx solid #faa307 !important;}text {color: #ff7029;}}.submit_box {width: 750rpx;height: 160rpx;background-color: #F1F1F1;position: fixed;bottom: 0;}.sub_btn {width: 80%;height: 88rpx;background: linear-gradient(-30deg, #dc4011 0%, #faa307 100%);border-radius: 44rpx;margin: 40rpx auto;font-size: 32rpx;font-weight: 700;color: #ffffff;text-align: center;line-height: 88rpx;}// 按钮原生会存在上下黑线,该属性去除button::after {border: none;}
</style>
  • 后台管理部分页面代码 charts.vue
<template><view><block v-for="(item,index) in dataList" :key="index"><view style="margin: 50rpx;">{{item.subjectContent}}</view><canvas :canvas-id="'id'+index" style="width: 350px; height: 300px;" ></canvas></block></view>
</template><script>// 引入外部 jsimport canvas from '@/static/canvas.js'export default {data() {return {baseUrl: '',dataList: []}},onReady() {// 获取全局变量 baseUrlthis.baseUrl = getApp().globalData.baseUrl;// 调用方法this.getData()},methods: {//从后端获取数据getData() {uni.showLoading({title: '数据加载中...'})uni.request({url: this.baseUrl + 'queryByGroup',method: "GET",data: {},success: (res) => {//console.log(res)let tempArr = res.datathis.dataList = tempArrlet arr = tempArr.sort(this.compare('sort')) //按对象内的sort字段进行排序数组// 延迟1秒等待canvas组件渲染完成,再调用方法绘画,否则绘画不成功setTimeout(function(){for (let x in arr) {// 调用外部方法并传入参数: canvas-id,数组,总数量canvas.canvasGraph('id'+x, arr[x].list, arr[x].list[0].total)}},1000)},fail: (err) => {uni.showToast({title: "网络请求失败!",icon: 'none',duration: 2000})},complete: () => {setTimeout(function(){uni.hideLoading()},1000)}})},//--- 数组内的对象按某个字段进行排序 ---//compare(property){return function(a,b){var value1 = a[property];var value2 = b[property];return value1 - value2;  //升序,  降序为value2 - value1}}}}
</script><style></style>
  • 后端使用 nodejs + mongoDB 搭建服务
  • 程序入口文件 app.js
const express = require('express');
const cors=require('cors');
const bodyParser = require('body-parser');
const app = express();//全局变量,数据库地址
global.G_url = "mongodb://127.0.0.1:27017";//处理跨域
app.use(cors()) 
//对post请求的请求体进行解析
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())//设置share文件夹下的所有文件能通过网址访问,用作静态文件web服务
app.use(express.static("./share"))//路由配置
const index=require('./routes/index.js')
const query=require('./routes/query.js')
const add=require('./routes/add.js')
const del=require('./routes/del.js')
const edit=require('./routes/edit.js')
const update=require('./routes/update.js')
const addAnswer=require('./routes/addAnswer.js')
const queryAnswer=require('./routes/queryAnswer.js')
const queryByGroup=require('./routes/queryByGroup.js')
const delAll=require('./routes/delAll.js')app.use('/index',index)
app.use('/query',query)
app.use('/add',add)
app.use('/del',del)
app.use('/edit',edit)
app.use('/update',update)
app.use('/addAnswer',addAnswer)
app.use('/queryAnswer',queryAnswer)
app.use('/queryByGroup',queryByGroup)
app.use('/delAll',delAll)//启动服务器
app.listen(3000,()=>{console.log('http://127.0.0.1:3000')
})
  • 对原始数据按题目名称进行分组,然后追加需要用到的字段,再把处理好的数据发给前端进行渲染。
// queryByGroup.jsconst express = require('express');
const router = express.Router();
const MongoClient = require("mongodb").MongoClient;const url = G_url; //G_url是全局变量,在app.js定义router.get('/', function(req, res, next) {// 调用方法dataOperate()/*操作数据库,异步方法*/async function dataOperate() {var allArr = []var arr = nullvar conn = nulltry {conn = await MongoClient.connect(url)// 定义使用的数据库和表const dbo = conn.db("mydb").collection("answer")// 查询所有arr = await dbo.find().toArray()// 调用 byGroup方法对原始数组按指定字段进行分组let groupBySubjectContent = byGroup(arr, 'subjectContent')// 循环执行for (var n in groupBySubjectContent) {let subjectContent = groupBySubjectContent[n].subjectContentlet nameList = groupBySubjectContent[n].list// 从原数组中过滤字段等于subjectContent ,取最后一个元素let lastArr = (arr.filter(item => item.subjectContent == subjectContent)).slice(-1)let sort = lastArr[0].sort// 计算数组中某个元素的累计数量let countedNameObj = nameList.reduce((prev, item) => {if (item in prev) {prev[item]++} else {prev[item] = 1}return prev}, {})// 一个对象分割为多个对象let list = []for (var key in countedNameObj) {var temp = {}temp.title = keytemp.money = countedNameObj[key]list.push(temp)}// 所有对象 money字段求和let listSum = list.reduce((prev, item) => {prev += item.moneyreturn prev}, 0)// 对象循环追加键值对for (var k in list) {list[k].total = listSumlist[k].value = (list[k].money / listSum).toFixed(4) //计算比例,保留4位小数list[k].color = randomColor(k) //指定颜色//list[k].color = '#' + ('00000' + (Math.random() * 0x1000000 << 0).toString(16)).substr(-6) //随机颜色}// 对象追加到数组allArr.push({"sort": sort,"subjectContent": subjectContent,"list": list})}//给前端返回数据res.send(allArr)} catch (err) {console.log("错误:" + err.message)} finally {//关闭数据库连接if (conn != null) conn.close()}}/*** 数据按字段分组处理* @param arr [Array] 被处理的数组* @param group_key [String] 分组字段*/function byGroup(arr, group_key) {let map = {}let res = []for (let i = 0; i < arr.length; i++) {let ai = arr[i]if (!map[ai[group_key]]) {// map[ai[group_key]] = [ai] //原始代码//optionContent是要筛选出来的字段map[ai[group_key]] = ai.optionContent.split(',')} else {// map[ai[group_key]].push(ai) //原始代码// split()通过指定分隔符对字符串进行分割,生成新的数组; arr = [...arr, ...arr2]  数组合并map[ai[group_key]] = [...map[ai[group_key]], ...ai.optionContent.split(',')]}}Object.keys(map).forEach(item => {res.push({[group_key]: item,list: map[item]})})return res}/**随机指定颜色**/function randomColor(index) {let colorList = ["#63b2ee","#76da91","#f8cb7f","#7cd6cf","#f89588","#9192ab","#efa666","#7898e1","#eddd86","#9987ce","#76da91","#63b2ee"]// let index = Math.floor(Math.random() * colorList.length)return colorList[index]}});module.exports = router;

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/625410.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

新年送长辈礼物怎么选?华为畅享70 Pro 给长辈的新年贴心机

随着春节的脚步越来越近&#xff0c;我们也在为如何表达对长辈的关爱而烦恼。新年送礼&#xff0c;不仅要表达心意&#xff0c;更要考虑到长辈的需求和习惯。今天&#xff0c;我为大家带来一款特别适合长辈的礼物——华为畅享70 Pro。 首先&#xff0c;最直观的感受就是“大”。…

Docker部署Traefik结合内网穿透远程访问Dashboard界面

文章目录 前言1. Docker 部署 Trfɪk2. 本地访问traefik测试3. Linux 安装cpolar4. 配置Traefik公网访问地址5. 公网远程访问Traefik6. 固定Traefik公网地址 前言 Trfɪk 是一个云原生的新型的 HTTP 反向代理、负载均衡软件&#xff0c;能轻易的部署微服务。它支持多种后端 (D…

手机视频转换gif怎么操作?一个小妙招教你手机在线制gif

在现代社会gif动图已经是一种非常流行的图片格式了。可以通过视频转换gif的方式将自己的想法和创意制作成gif动图与好友进行分享斗图。那么&#xff0c;当我们想要在手机上完成视频转换成gif动图是应该怎么办呢&#xff1f;通过使用手机端的gif动图制作&#xff08;https://www…

uniapp 权限申请插件(权限使用说明) Ba-Permissions

简介&#xff08;下载地址&#xff09; Ba-Permissions 是一款权限申请插件&#xff0c;支持权限使用说明弹窗&#xff0c;满足市场审核需求。支持自定义权限申请&#xff0c;也支持快速申请定位、相机、媒体、文件、悬浮窗等常见权限。 支持权限使用说明弹窗&#xff0c;满足…

16 命令行模式

命令行模式 将行为的执行与与行为的调用通过命令分离&#xff0c;行为的的调用者不需要知道具体是哪个类执行的&#xff0c;他们之间通过命令连接。 demo的目录结构 命令的执行者&#xff08;接口&#xff09; package behavioralpattern.commandpattern.actuator;import ja…

el-tabs那些事

去除el-tab-pane的内边距 :deep(.el-tabs--border-card > .el-tabs__content) {padding: 0; }

VMware workstation安装Fedora-Server-39-1.5虚拟机并配置网络

VMware workstation安装Fedora-Server-39-1.5虚拟机并配置网络 Fedora包含的软件以自由及开放源码许可来发布&#xff0c;并旨在成为该技术领域的领先者。Fedora在专注创新、抢先集成新技术、与上游Linux社区紧密工作方面拥有良好名声。该文档适用于在VMware workstation平台安…

java-方法:函数、过程

方法作用 - 封装一段特定的业务逻辑功能 - 尽可能的独立&#xff0c;一个方法只干一件事 - 方法可以被反复多次调用 - 减少代码重复&#xff0c;有利于代码复用&#xff0c;有利于代码维护 定义方法&#xff1a;五要素 ​ 修饰词 返回值类型 方法名(参数列表…

矩阵快速幂算法总结

题目链接 活动 - AcWing 本课程系统讲解常用算法与数据结构的应用方式与技巧。https://www.acwing.com/problem/content/1305/ 题解 代码 #include <cstdio> #include <cstring> #include <iostream> #include <algorithm>using namespace std;type…

MySQL多表关联查询练习题

一、创建表的素材 1.创建student和score表 CREATE TABLE student ( id INT(10) NOT NULL UNIQUE PRIMARY KEY , name VARCHAR(20) NOT NULL , sex VARCHAR(4) , birth YEAR, department VARCHAR(20) , address VARCHAR(50) ); 创建score表。SQL代码如下&#xff1a; …

Android的setContentView流程

一.Activity里面的mWindow是啥 在ActivityThread的performLaunchActivity方法里面&#xff1a; private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {ActivityInfo aInfo r.activityInfo;if (r.packageInfo null) {r.packageInfo getP…

15 万奖金!开放原子开源大赛 OpenAnolis -云原生赛题报名开始

开放原子开源基金会牵头发起的首届“开放原子开源大赛”&#xff0c;旨在联合开源组织、企事业单位、高等院校、科研院所、行业组织、投融资机构等多方资源&#xff0c;充分发挥产业链生态上下游的协同能力&#xff0c;基于开源共享、共建共治的原则共同举办。大赛搭建面向全球…

教育新势力:多端口知识付费小程序重塑在线教育生态

随着知识付费市场的蓬勃发展&#xff0c;多端口知识付费小程序已成为课程销售的关键工具。本文将探讨多端口知识付费小程序的重要性和乔拓云教育系统的功能&#xff0c;帮助您在网上成功销售课程。 一、多端口知识付费小程序的优点 多端口知识付费小程序具有多渠道触达用户、提…

IOS 相机权限申请-swift

配置描述 在Info.plist文件中&#xff0c;新建一个键值对Privacy - Camera Usage Description&#xff08;或者NSCameraUsageDescription&#xff09;&#xff0c;值为申请描述说明&#xff0c;自定义的 申请 然后在需要申请的文件中导入AVFoundation import AVFoundation…

你觉得哪个软件写verilog体验最好?

**“你觉得哪个软件写verilog体验最好&#xff1f;”**这个问题是我再网络上看到的一个热点话题&#xff0c;浏览量高达733911&#xff0c;引起大家的广泛讨论。移知教育小编特意请教了行业大咖&#xff0c;下面为大家分享解答&#xff0c;希望能为大家带来帮助。 有几个流行的…

跟着cherno手搓游戏引擎【4】窗口抽象、GLFW配置、窗口事件

引入GLFW&#xff1a; 在vendor里创建GLFW文件夹&#xff1a; 在github上下载&#xff0c;把包下载到GLFW包下。 GitHub - TheCherno/glfw: A multi-platform library for OpenGL, OpenGL ES, Vulkan, window and input修改SRC/premake5.lua的配置&#xff1a;12、13、15、36…

分布式架构理论:从头梳理分布式架构的重难点

文章目录 一、分布式架构 - 系统理论1、分布式一致性与CAP理论2、BASE理论3、分布式一致性算法&#xff1a;Raft&#xff08;1&#xff09;Paxos算法&#xff08;2&#xff09;Raft算法&#xff08;3&#xff09;共识算法&#xff1a;拜占庭将军问题 4、脑裂现象和Lease机制&am…

AI模型理解误区:微调垂直行业-VS-企业专属知识库或AI助理

概述 企业定制私有化大模型的区别&#xff0c;分为训练大模型和调用大模型两种方向&#xff0c;以及企业自己的智能客服的实现方法。 - 企业定制的私有化大模型与一般的大模型不同&#xff0c;需要高成本训练。- 企业可以选择调用已经训练好的大模型来应用。- 企业可以使用向量…

今天吃什么小游戏(基于Flask框架搭建的简单应用程序,用于随机选择午餐选项。代码分为两部分:Python部分和HTML模板部分)

今天吃什么 一个简单有趣的外卖点饭网站&#xff0c;不知道吃什么的时候&#xff0c;都可以用它自动决定你要吃的&#xff0c;包括各种烧烤、火锅、螺蛳粉、刀削面、小笼包、麦当劳等午餐全部都在内。点击开始它会随意调出不同的午餐&#xff0c;点击停止就会挑选一个你准备要吃…

如何用ArcGIS制作城市用地适应性评价

01概述 “城市用地适宜性评价是城市总体规划的一项重要前期工作&#xff0c;它首先对工程地质、社会经济和生态环境等要素进行单项用地适宜性评价&#xff0c;然后用地图叠加技术根据每个因子所占权重生成综合的用地适宜性评价结果&#xff0c;俗称“千层饼模式”。 做用地适…