微信小程序实用代码段(收藏版)

前端之家收集整理的这篇文章主要介绍了微信小程序实用代码段(收藏版)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

前言

排名不分先后,按自己的习惯来的。

总结经验,不喜勿喷哦~

一、tab切换

  1. <view class=" {{currentTab==0 ? 'select' : ''}}" data-current="0" bindtap="swichNav"> tab1</view>
  2. <view class=" {{currentTab==1 ? 'select' : ''}}" data-current="1" bindtap="swichNav"> tab2</view>
  3.  
  4. Page({
  5. data:{
  6. // tab切换
  7. currentTab: 0,},swichNav: function (e) {
  8. var that = this;
  9. if (this.data.currentTab === e.target.dataset.current) {
  10. return false;
  11. } else {
  12. that.setData({
  13. currentTab: e.target.dataset.current
  14. })
  15. }
  16. },})

二、swiper切换

  1. <view>
  2. <text class=" {{currentTab==0 ? 'select' : ''}}" data-current="0" bindtap="swichNav">tab1</text>
  3. <text class=" {{currentTab==1 ? 'select' : ''}}" data-current="1" bindtap="swichNav">tab2 </text>
  4. <text class=" {{currentTab==2 ? 'select' : ''}}" data-current="2" bindtap="swichNav">tab3 </text>
  5. </view>
  6. <swiper current="{{currentTab}}" bindchange="bindChange" class='swp' style="height: {{aheight?aheight+'px':'auto'}}">
  7. <swiper-item>页面1</swiper-item>
  8. <swiper-item>页面2</swiper-item>
  9. <swiper-item>页面3</swiper-item>
  10. </swiper>
  11.  
  12. Page({
  13. data:{
  14. currentTab: 0,aheight: ''
  15. },// 滑动切换
  16. bindChange: function (e) {
  17. var that = this;
  18. that.setData({
  19. currentTab: e.detail.current
  20. });
  21. },//点击tab切换
  22. swichNav: function (e) {
  23. var that = this;
  24. if (this.data.currentTab === e.target.dataset.current) {
  25. return false;
  26. } else {
  27. that.setData({
  28. currentTab: e.target.dataset.current
  29. })
  30. }
  31. },// swiper 自适应高度
  32. onLoad: function (options) {
  33. var that = this
  34. wx.getSystemInfo({
  35. success: function (res) {
  36. that.setData({
  37. aheight: res.screenHeight
  38. });
  39. }
  40. })
  41. },})

三、图片上传

  1. <view class="ovf img_Box">
  2. <block wx:for="{{img_arr}}" wx:key="{{item.id}}" bindtap="del">
  3. <view class='logoinfo' data-index="{{index}}">
  4. <view class="del">
  5. <image src="http://192.168.2.61/wx_ry/del.png" mode="widthFix" bindtap="deleteImage"></image>
  6. </view>
  7. <image src='{{item}}' mode="widthFix"></image>
  8. </view>
  9. </block>
  10. <view class="upload">
  11. <image src="http://192.168.2.61/wx_ry/add.png" mode="widthFix" bindtap="upimg"></image>
  12. </view>
  13. </view>
  14.  
  15. .upload { width: 20%; float: left; margin-top:33rpx ; }
  16. .upload image{ width: 100%; }
  17. .logoinfo{ width: 20%; float: left; margin-right:2% ; }
  18. .del{ width: 20%; float: right; }
  19. .del image{ width: 100%; }
  20. .logoinfo image{ width: 100%; }
  21.  
  22. page({
  23. data:{
  24. img_arr: []
  25. },// 图片上传
  26. upimg: function () {
  27. var that = this;
  28. if (this.data.img_arr.length < 3) {
  29. wx.chooseImage({
  30. sizeType: ['original','compressed'],success: function (res) {
  31. that.setData({
  32. img_arr: that.data.img_arr.concat(res.tempFilePaths),})
  33.  
  34. }
  35. })
  36. } else {
  37. wx.showToast({
  38. title: '最多上传三张图片',icon: 'loading',duration: 3000
  39. });
  40. }
  41. },// 删除图片
  42. deleteImage: function (e) {
  43. var that = this;
  44. var index = e.currentTarget.dataset.index; //获取当前长按图片下标
  45. console.log(that.data.img_arr)
  46. wx.showModal({
  47. title: '提示',content: '确定要删除图片吗?',success: function (res) {
  48. if (res.confirm) {
  49. console.log('点击确定了');
  50. that.data.img_arr.splice(index,1);
  51. } else if (res.cancel) {
  52. console.log('点击取消了');
  53. return false;
  54. }
  55. that.setData({
  56. img_arr: that.data.img_arr
  57. });
  58. }
  59. })
  60. },// 上传
  61. upload: function () {
  62. var that = this
  63. for (var i = 0; i < this.data.img_arr.length; i++) {
  64. wx.uploadFile({
  65. url: 'https:***/submit',filePath: that.data.img_arr[i],name: 'content',formData: adds,success: function (res) {
  66. console.log(res)
  67. if (res) {
  68. wx.showToast({
  69. title: '已提交发布!',duration: 3000
  70. });
  71. }
  72. }
  73. })
  74. }
  75. this.setData({
  76. formdata: ''
  77. })
  78. },// 提交
  79. formSubmit: function (e) {
  80. console.log('form发生了submit事件,携带数据为:',e.detail.value)
  81. }
  82. })

四、scroll-view滚动页

  1. <scroll-view class="scroll-view_H " scroll-x="true" bindscroll="scroll">
  2. <view class="fxjx_b1" style="display: inline-block">
  3. <view class="listb">1</view>
  4. </view>
  5. <view class="fxjx_b1" style="display: inline-block">
  6. <view class="listb">2</view>
  7. </view>
  8. </scroll-view>
  9.  
  10. .scroll-view_H{ white-space: nowrap; height: 600rpx; }
  11. .listb{ padding: 25rpx; white-space: normal; }

五、授权登录

app.js

  1. //app.js
  2. App({
  3. globalData: {
  4. userInfo: null,unionid:null,token:''
  5. },onLaunch: function () {
  6. /* 已授权之后,自动获取用户信息 */
  7. // 判断是否授权
  8. wx.getSetting({
  9. success: (res) => { //箭头函数为了处理this的指向问题
  10. if (res.authSetting["scope.userInfo"]) {
  11. console.log("已授权");
  12. // 获取用户信息
  13. wx.getUserInfo({
  14. success: (res) => { //箭头函数为了处理this的指向问题
  15. // this.globalData.isok=true
  16. this.globalData.token='ok'
  17. var that =this
  18. console.log(res.userInfo); //用户信息结果
  19. wx.getStorage({
  20. key: 'unionid',success(res) {
  21. that.globalData.unionid=res.data
  22. }
  23. })
  24. this.globalData.userInfo = res.userInfo;
  25. if (this.userInfoReadyCallback) { //当index.js获取到了globalData就不需要回调函数了,所以回调函数需要做做一个判断,如果app.js中有和这个回调函数,那么就对这个函数进行调用,并将请求到的结果传到index.js中
  26. this.userInfoReadyCallback(res.userInfo);
  27. }
  28. }
  29. })
  30. }
  31. else{
  32. console.log("未授权");
  33. wx.removeStorage({
  34. key: 'unionid'
  35. })
  36. }
  37. }
  38. })
  39. }
  40. })

wxml

  1. <button open-type="getUserInfo" lang="zh_CN" bindgetuserinfo="onGotUserInfo" class="btn" data-url='../yzzs/yzzs'>
  2. 防疫针助手
  3. </button>

index.js

  1. // pages/index/index.js
  2. const app = getApp()
  3. Page({
  4. data: {
  5. token:''
  6. },onGotUserInfo: function (e) {
  7. var that = this
  8. if (this.data.token != 'ok' && app.globalData.token != 'ok') {
  9. wx.getSetting({
  10. success: (res) => { //箭头函数为了处理this的指向问题
  11. if (res.authSetting["scope.userInfo"]) {
  12. wx.login({
  13. success: function (data) {
  14. console.log('获取登录 Code:' + data.code)
  15. var postData = {
  16. code: data.code
  17. };
  18. wx.request({
  19. url: 'https://m.renyiwenzhen.com/rymember.PHP?mod=xcxlogin&code=' + postData.code + '&nickname=' + e.detail.userInfo.nickName,data: {},header: {
  20. 'content-type': 'application/json'
  21. },success: function (res) {
  22. console.log(res.data);
  23. that.data.token='ok';
  24. wx.setStorage({
  25. key: "unionid",data: res.data.unionid
  26. })
  27. wx.navigateTo({
  28. url: e.target.dataset.url
  29. })
  30. },fail: function () {
  31. console.log('1');
  32. }
  33. })
  34. },fail: function () {
  35. console.log('登录获取Code失败!');
  36. }
  37. })
  38. }
  39. }
  40. })
  41. } else{
  42. wx.navigateTo({
  43. url: e.target.dataset.url
  44. })
  45. }
  46. }
  47. })

六、发送请求

  1. wx.request({
  2. url: 'https://m.renyiwenzhen.com/xcx_ajax.PHP?action=babylist',//仅为示例,并非真实的接口地址
  3. method: 'post',data: {
  4. unionid: uni
  5. },header: {
  6. 'content-type': 'application/x-www-form-urlencoded' // 默认值
  7. },success(res) {
  8. // console.log(uni)
  9. console.log(res.data)
  10. that.setData({
  11. list: res.data.bblist
  12. })
  13. }
  14. })

七、标题栏及底部

全局标题

  1. "window": {
  2. "backgroundTextStyle": "light","navigationBarBackgroundColor": "#3EC8C8","navigationBarTitleText": "乳孕呵护","navigationBarTextStyle": "white"
  3. }

局部标题

  1. {
  2. "usingComponents": {},"navigationBarBackgroundColor": "#fff","navigationBarTextStyle": "black","navigationBarTitleText": "附近医院"
  3. }

全局底部

  1. "tabBar": {
  2. "color": "#e4e4e4","selectedColor": "#333","list": [
  3. {
  4. "pagePath": "pages/index/index","text": "发现","iconPath": "./images/find.png","selectedIconPath": "./images/finded.png"
  5. },{
  6. "pagePath": "pages/his/his","text": "医院","iconPath": "./images/his.png","selectedIconPath": "./images/hised.png"
  7. },{
  8. "pagePath": "pages/stu/stu","text": "经验","iconPath": "./images/stu.png","selectedIconPath": "./images/stued.png"
  9. },{
  10. "pagePath": "pages/my/my","text": "我的","iconPath": "./images/my.png","selectedIconPath": "./images/myed.png"
  11. }
  12. ]
  13. }

八、navigator

1、wxml

  1. <navigator url="/pages/hishome/hishome" open-type="navigate" hover-class="none">
  2. 底部栏没有的路由
  3. </navigator>
  4. <navigator open-type="switchTab" url="/pages/his/his" hover-class="none">
  5. 底部栏有的路由
  6. </navigator>

2、js

  1. go: function (e) {
  2. wx.navigateTo({
  3. url: '../eatxq/eatxq?id=' + e.currentTarget.dataset.id + "&name=" + e.currentTarget.dataset.name
  4. })
  5. }

九、加载条

  1. <loading hidden="{{onff}}">加载中</loading>
  2. <view>页面</view>

加载完成true

  1. wx.request({
  2. url: 'https://m.renyiwenzhen.com/xcx_ajax.PHP?action=caneatsearch',method: 'post',data: {
  3. search: options.search
  4. },success(res) {
  5. that.setData({
  6. list: res.data.fllist,onff: true
  7. })
  8. }
  9. })

十、富文本处理

  1. <view class="txt">
  2. <rich-text nodes="{{msg}}" ></rich-text>
  3. </view>

利用正则修改收到的数据

  1. wx.request({
  2. url: 'https://m.renyiwenzhen.com/xcx_ajax.PHP?action=cjdetail',data: {
  3. id: options.id
  4. },header: {
  5. 'content-type': 'application/x-www-form-urlencoded' // 默认值
  6. },success(res) {
  7. that.setData({
  8. msg: res.data.cjmag.cjxq.replace(/\<p>/g,"<p style='line-height: 24px; font-size:15px;text-align: justify;margin:15px 0;'>")
  9. })
  10. }
  11. })

十一、filter过滤数据

1、在根目录下的utils文件夹里创建一个名为filter.wxs文件 2、写入自己要定义的条件

  1. var xb=function (v) {
  2. var xingb=''
  3. if(v==1){
  4. xingb="男宝宝"
  5. }
  6. else{
  7. xingb="女宝宝"
  8. }
  9. return xingb
  10. }
  11. module.exports = {
  12. xb:xb
  13. }

3、在页面中引入使用

  1. <wxs src="../../utils/filter.wxs" module="filter" />
  2. <view><text>{{filter.xb(isxb)}}</text></view>

十二、检测版本更新

app.js

  1. onLaunch: function () {
  2. if (wx.canIUse('getUpdateManager')) {
  3. const updateManager = wx.getUpdateManager()
  4. updateManager.onCheckForUpdate(function (res) {
  5. // 请求完新版本信息的回调
  6. if (res.hasUpdate) {
  7. updateManager.onUpdateReady(function () {
  8. wx.showModal({
  9. title: '更新提示',content: '新版本已经准备好,是否重启应用?',success: function (res) {
  10. // res: {errMsg: “showModal: ok”,cancel: false,confirm: true}
  11. if (res.confirm) {
  12. // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
  13. updateManager.applyUpdate()
  14. }
  15. }
  16. })
  17. })
  18. updateManager.onUpdateFailed(function () {
  19. // 新的版本下载失败
  20. wx.showModal({
  21. title: '已经有新版本了哟~',content: '新版本已经上线啦,请您删除当前小程序,重新搜索打开哟'
  22. })
  23. })
  24. }
  25. })
  26. }
  27. }

十三、点击tab跳转对应的的项目页面

我们经常会遇到这种需求:

点击对应的的tab,这里比如说是A页。

微信小程序实用代码段(收藏版)


跳转到对应项目的页面,这里比如说是B页。

微信小程序实用代码段(收藏版)


A页:

  1. <view class="project_nab ovf">
  2. <view class="on"> 详情 </view>
  3. <view class="project_item" bindtap="goitem" data-url='jd'>建档</view>
  4. <view class="project_item" bindtap="goitem" data-url='cj'>产检</view>
  5. <view class="project_item" bindtap="goitem" data-url='fm'>分娩</view>
  6. </view>
  7.  
  8. goitem:function (e) {
  9. wx.navigateTo({
  10. url: '/pages/item/item?url=' + e.target.dataset.url
  11. })
  12. },

B页:

  1. <view class="top1 ovf">
  2. <view class="" ><navigator url="/pages/hishome/hishome" open-type="navigate">详情</navigator></view>
  3. <view class=" {{currentTab==0 ? 'select' : ''}}" data-current="0" bindtap="swichNav"> 产检 </view>
  4. <view class=" {{currentTab==1 ? 'select' : ''}}" data-current="1" bindtap="swichNav"> 建档 </view>
  5. <view class=" {{currentTab==2 ? 'select' : ''}}" data-current="2" bindtap="swichNav"> 分娩 </view>
  6. </view>
  7.  
  8. onLoad: function (options) {
  9. var that = this;
  10. console.log(options.url)
  11. if (options.url === 'cj') {
  12. that.setData({
  13. currentTab: '0',btn: '产检',set: 'cj'
  14. });
  15. } else if (options.url === 'jd') {
  16. that.setData({
  17. currentTab: '1',btn: '建档',set: 'jd'
  18. });
  19. } else {
  20. that.setData({
  21. currentTab: '2',btn: '分娩',set: 'fm'
  22. });
  23. }
  24. }

总结

以上所述是小编给大家介绍的微信小程序实用代码段,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

猜你在找的JavaScript相关文章