实现微信小程序投票功能,需要使用微信小程序提供的API来处理用户投票和数据存储。以下是一个简单的投票功能示例,包括用户投票、数据存储和结果显示。
在app.js
中,设置一个全局变量来存储投票结果:
1 2 3 4 5 6 7 8 9 | App({ globalData: { votes: { option1: 0, option2: 0, option3: 0 } } }) |
在pages/index/index.js
中,实现投票功能:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | Page({ data: { voteOption: '' }, onLoad: function () { // 监听用户点击选项进行投票 this .setData({ voteOption: 'option1' // 默认选中第一个选项 }) }, vote: function (event) { const option = event.currentTarget.dataset.option // 获取用户点击的选项 const votes = getApp().globalData.votes // 获取全局变量投票结果 // 更新投票结果 votes[option]++ // 更新页面显示结果 this .setData({ voteOption: option, voteResult: votes }) // 存储投票结果到本地缓存中,有效期为1天 wx.setStorageSync( 'votes' , votes) } }) |
3.在pages/index/index.wxml
中,显示投票选项和结果显示
1 2 3 | {{item}} 当前投票结果:{{voteResult}} |
在pages/index/index.wxss
中,设置样式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | .container { display : flex; flex-direction : column; align-items : center ; justify-content : center ; height : 100 vh; } .vote-option { padding : 20px ; border : 1px solid #ccc ; border-radius : 5px ; cursor : pointer ; } .vote-result { padding : 20px ; font-size : 20px ; font-weight : bold ; } |