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


Posted in Javascript onDecember 17, 2019

前言

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

总结经验,不喜勿喷哦~

一、tab切换

<view class=" {{currentTab==0 ? 'select' : ''}}" data-current="0" bindtap="swichNav"> tab1</view>
<view class=" {{currentTab==1 ? 'select' : ''}}" data-current="1" bindtap="swichNav"> tab2</view>

Page({
data:{
 // tab切换 
 currentTab: 0,
},
swichNav: function (e) {
 var that = this;
 if (this.data.currentTab === e.target.dataset.current) {
 return false;
 } else {
 that.setData({
 currentTab: e.target.dataset.current
 })
 }
 },

})

二、swiper切换

<view>
  <text class=" {{currentTab==0 ? 'select' : ''}}" data-current="0" bindtap="swichNav">tab1</text>
  <text class=" {{currentTab==1 ? 'select' : ''}}" data-current="1" bindtap="swichNav">tab2 </text>
  <text class=" {{currentTab==2 ? 'select' : ''}}" data-current="2" bindtap="swichNav">tab3 </text>
  </view>
 <swiper current="{{currentTab}}" bindchange="bindChange" class='swp' style="height: {{aheight?aheight+'px':'auto'}}">
 <swiper-item>页面1</swiper-item>
 <swiper-item>页面2</swiper-item>
 <swiper-item>页面3</swiper-item>
 </swiper>

Page({
data:{
 currentTab: 0,
 aheight: ''
},
// 滑动切换
 bindChange: function (e) {
 var that = this;
 that.setData({
 currentTab: e.detail.current
 });
 },
 //点击tab切换
 swichNav: function (e) {
 var that = this;
 if (this.data.currentTab === e.target.dataset.current) {
 return false;
 } else {
 that.setData({
 currentTab: e.target.dataset.current
 })
 }
 },
 // swiper 自适应高度
 onLoad: function (options) {
 var that = this
 wx.getSystemInfo({
 success: function (res) {
 that.setData({
  aheight: res.screenHeight
 });
 }
 })
 },
})

三、图片上传

<view class="ovf img_box">
  <block wx:for="{{img_arr}}" wx:key="{{item.id}}" bindtap="del">
  <view class='logoinfo' data-index="{{index}}">
   <view class="del">
   <image src="http://192.168.2.61/wx_ry/del.png" mode="widthFix" bindtap="deleteImage"></image>
   </view>
   <image src='{{item}}' mode="widthFix"></image>
  </view>
  </block>
  <view class="upload">
   <image src="http://192.168.2.61/wx_ry/add.png" mode="widthFix" bindtap="upimg"></image>
  </view>
 </view>

.upload { width: 20%; float: left; margin-top:33rpx ; }
.upload image{ width: 100%; }
.logoinfo{ width: 20%; float: left; margin-right:2% ; }
.del{ width: 20%; float: right; }
.del image{ width: 100%; }
.logoinfo image{ width: 100%; }

page({
data:{
 img_arr: []
},
 // 图片上传
 upimg: function () {
 var that = this;
 if (this.data.img_arr.length < 3) {
 wx.chooseImage({
 sizeType: ['original', 'compressed'],
 success: function (res) {
  that.setData({
  img_arr: that.data.img_arr.concat(res.tempFilePaths),
  })

 }
 })
 } else {
 wx.showToast({
 title: '最多上传三张图片',
 icon: 'loading',
 duration: 3000
 });
 }
 },
 // 删除图片
 deleteImage: function (e) {
 var that = this;
 var index = e.currentTarget.dataset.index; //获取当前长按图片下标
 console.log(that.data.img_arr)
 wx.showModal({
 title: '提示',
 content: '确定要删除此图片吗?',
 success: function (res) {
 if (res.confirm) {
  console.log('点击确定了');
  that.data.img_arr.splice(index, 1);
 } else if (res.cancel) {
  console.log('点击取消了');
  return false;
 }
 that.setData({
  img_arr: that.data.img_arr
 });
 }
 })
 },
 // 上传
 upload: function () {
 var that = this
 for (var i = 0; i < this.data.img_arr.length; i++) {
 wx.uploadFile({
 url: 'https:***/submit',
 filePath: that.data.img_arr[i],
 name: 'content',
 formData: adds,
 success: function (res) {
  console.log(res)
  if (res) {
  wx.showToast({
  title: '已提交发布!',
  duration: 3000
  });
  }
 }
 })
 }
 this.setData({
 formdata: ''
 })
 },
 // 提交
 formSubmit: function (e) {
 console.log('form发生了submit事件,携带数据为:', e.detail.value)
 }
})

四、scroll-view滚动页

<scroll-view class="scroll-view_H " scroll-x="true" bindscroll="scroll">
 <view class="fxjx_b1" style="display: inline-block">
 <view class="listb">1</view>
 </view>
 <view class="fxjx_b1" style="display: inline-block">
 <view class="listb">2</view>
 </view>
 </scroll-view>

.scroll-view_H{ white-space: nowrap; height: 600rpx; }
.listb{ padding: 25rpx; white-space: normal; }

五、授权登录

app.js

//app.js
App({
 globalData: {
 userInfo: null,
 unionid:null,
 token:''
 },
 onLaunch: function () {
 /* 已授权之后,自动获取用户信息 */
 // 判断是否授权
 wx.getSetting({
 success: (res) => { //箭头函数为了处理this的指向问题 
 if (res.authSetting["scope.userInfo"]) {
 console.log("已授权");
 // 获取用户信息
 wx.getUserInfo({
  success: (res) => { //箭头函数为了处理this的指向问题
  // this.globalData.isok=true
  this.globalData.token='ok'
  var that =this
  console.log(res.userInfo); //用户信息结果
  wx.getStorage({
  key: 'unionid',
  success(res) {
  that.globalData.unionid=res.data
  }
  })
  this.globalData.userInfo = res.userInfo;
  if (this.userInfoReadyCallback) { //当index.js获取到了globalData就不需要回调函数了,所以回调函数需要做做一个判断,如果app.js中有和这个回调函数,那么就对这个函数进行调用,并将请求到的结果传到index.js中
  this.userInfoReadyCallback(res.userInfo);
  }
  }
 })
 }
 else{
 console.log("未授权");
 wx.removeStorage({
  key: 'unionid'
 })
 }
 }
 })
 }
})

wxml

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

index.js

// pages/index/index.js
const app = getApp()
Page({
 data: {
 token:''
 },
 onGotUserInfo: function (e) {
 var that = this
 if (this.data.token != 'ok' && app.globalData.token != 'ok') {
 wx.getSetting({
 success: (res) => { //箭头函数为了处理this的指向问题 
  if (res.authSetting["scope.userInfo"]) {
  wx.login({
  success: function (data) {
  console.log('获取登录 Code:' + data.code)
  var postData = {
   code: data.code
  };
  wx.request({
   url: 'https://m.renyiwenzhen.com/rymember.php?mod=xcxlogin&code=' + postData.code + '&nickname=' + e.detail.userInfo.nickName,
   data: {},
   header: {
   'content-type': 'application/json'
   },
   success: function (res) {
   console.log(res.data);
   that.data.token='ok';
   wx.setStorage({
   key: "unionid",
   data: res.data.unionid
   })
   wx.navigateTo({
   url: e.target.dataset.url
   })
   },
   fail: function () {
   console.log('1');
   }
  })
  },
  fail: function () {
  console.log('登录获取Code失败!');
  }
  })
  }
 }
 })
 } else{
 wx.navigateTo({
 url: e.target.dataset.url
 })
 }
 }
})

六、发送请求

wx.request({
  url: 'https://m.renyiwenzhen.com/xcx_ajax.php?action=babylist', //仅为示例,并非真实的接口地址
  method: 'post',
  data: {
  unionid: uni
  },
  header: {
  'content-type': 'application/x-www-form-urlencoded' // 默认值
  },
  success(res) {
  // console.log(uni)
  console.log(res.data)
  that.setData({
  list: res.data.bblist
  })
  }
  })

七、标题栏及底部栏

全局标题栏

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

局部标题栏

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

全局底部栏

"tabBar": {
 "color": "#e4e4e4",
 "selectedColor": "#333",
 "list": [
 {
 "pagePath": "pages/index/index",
 "text": "发现",
 "iconPath": "./images/find.png",
 "selectedIconPath": "./images/finded.png"
 },
 {
 "pagePath": "pages/his/his",
 "text": "医院",
 "iconPath": "./images/his.png",
 "selectedIconPath": "./images/hised.png"
 },
 {
 "pagePath": "pages/stu/stu",
 "text": "经验",
 "iconPath": "./images/stu.png",
 "selectedIconPath": "./images/stued.png"
 },
 {
 "pagePath": "pages/my/my",
 "text": "我的",
 "iconPath": "./images/my.png",
 "selectedIconPath": "./images/myed.png"
 }
 ]
 }

八、navigator

1、wxml

<navigator url="/pages/hishome/hishome" open-type="navigate" hover-class="none"> 
底部栏没有的路由
</navigator>
<navigator open-type="switchTab" url="/pages/his/his" hover-class="none">
底部栏有的路由
</navigator>

2、js

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

九、加载条

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

加载完成true

wx.request({
  url: 'https://m.renyiwenzhen.com/xcx_ajax.php?action=caneatsearch', 
  method: 'post',
  header: {
  'content-type': 'application/x-www-form-urlencoded' // 默认值
  },
  data: {
  search: options.search
  },
  success(res) {
  that.setData({
  list: res.data.fllist,
  onff: true
  })
  }
  })

十、富文本处理

<view class="txt">
 <rich-text nodes="{{msg}}" ></rich-text>
 </view>

利用正则修改收到的数据

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

十一、filter过滤数据

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

var xb=function (v) {
 var xingb=''
 if(v==1){
 xingb="男宝宝"
 }
 else{
 xingb="女宝宝"
 }
 return xingb
}
module.exports = {
 xb:xb
}

3、在页面中引入使用

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

十二、检测版本更新

app.js

onLaunch: function () {
 if (wx.canIUse('getUpdateManager')) {
 const updateManager = wx.getUpdateManager()
 updateManager.onCheckForUpdate(function (res) {
 // 请求完新版本信息的回调
 if (res.hasUpdate) {
  updateManager.onUpdateReady(function () {
  wx.showModal({
  title: '更新提示',
  content: '新版本已经准备好,是否重启应用?',
  success: function (res) {
  // res: {errMsg: “showModal: ok”, cancel: false, confirm: true}
  if (res.confirm) {
   // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
   updateManager.applyUpdate()
  }
  }
  })
  })
  updateManager.onUpdateFailed(function () {
  // 新的版本下载失败
  wx.showModal({
  title: '已经有新版本了哟~',
  content: '新版本已经上线啦,请您删除当前小程序,重新搜索打开哟'
  })
  })
 }
 })
 }
}

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

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

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

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

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

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

A页:

<view class="project_nab ovf">
    <view class="on"> 详情 </view>
    <view class="project_item" bindtap="goitem" data-url='jd'>建档</view>
    <view class="project_item" bindtap="goitem" data-url='cj'>产检</view>
    <view class="project_item" bindtap="goitem" data-url='fm'>分娩</view>
   </view>

 goitem:function (e) {
 wx.navigateTo({
  url: '/pages/item/item?url=' + e.target.dataset.url
 })
 },

B页:

<view class="top1 ovf">
    <view class="" ><navigator url="/pages/hishome/hishome" open-type="navigate">详情</navigator></view>
    <view class=" {{currentTab==0 ? 'select' : ''}}" data-current="0" bindtap="swichNav"> 产检 </view>
    <view class=" {{currentTab==1 ? 'select' : ''}}" data-current="1" bindtap="swichNav"> 建档 </view>
    <view class=" {{currentTab==2 ? 'select' : ''}}" data-current="2" bindtap="swichNav"> 分娩 </view>
  </view>

 onLoad: function (options) {
 var that = this;
 console.log(options.url)
 if (options.url === 'cj') {
  that.setData({
  currentTab: '0',
  btn: '产检',
  set: 'cj'
  });
 } else if (options.url === 'jd') {
  that.setData({
  currentTab: '1',
  btn: '建档',
  set: 'jd'
  });
 } else {
  that.setData({
  currentTab: '2',
  btn: '分娩',
  set: 'fm'
  });
 } 
 }

总结

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

Javascript 相关文章推荐
EasyUi tabs的高度与宽度根据IE窗口的变化自适应代码
Oct 26 Javascript
js中判断Object、Array、Function等引用类型对象是否相等
Aug 29 Javascript
原生javascript实现的分页插件pagenav
Aug 28 Javascript
scrollWidth,clientWidth,offsetWidth的区别
Jan 13 Javascript
jQuery中cookie插件用法实例分析
Dec 04 Javascript
JavaScript如何实现在文本框(密码框)输入提示语
Dec 25 Javascript
轻松实现jquery手风琴效果
Jan 14 Javascript
JavaScript+html5 canvas实现本地截图教程
Apr 16 Javascript
WebSocket+node.js创建即时通信的Web聊天服务器
Aug 08 Javascript
js方法数据验证的简单实例
Sep 17 Javascript
纯js实现html转pdf的简单实例(推荐)
Feb 16 Javascript
微信小程序 标签传入数据
May 08 Javascript
微信小程序修改数组长度的问题的解决
Dec 17 #Javascript
微信小程序利用云函数获取手机号码
Dec 17 #Javascript
ant design实现圈选功能
Dec 17 #Javascript
15分钟学会vue项目改造成SSR(小白教程)
Dec 17 #Javascript
微信小程序获取复选框全选反选选中的值(实例代码)
Dec 17 #Javascript
微信小程序实现多选框全选与反全选及购物车中删除选中的商品功能
Dec 17 #Javascript
TypeScript高级用法的知识点汇总
Dec 17 #Javascript
You might like
ajax 的post方法实例(带循环)
2011/07/04 PHP
php curl选项列表(超详细)
2013/07/01 PHP
php str_getcsv把字符串解析为数组的实现方法
2017/04/05 PHP
PHP中的empty、isset、isnull的区别与使用实例
2019/03/22 PHP
php扩展开发入门demo示例
2019/09/23 PHP
JS 页面自动加载函数(兼容多浏览器)
2009/05/18 Javascript
Jquery.addClass始终无效原因分析
2013/09/08 Javascript
判断javascript的数据类型(示例代码)
2013/12/11 Javascript
JS冒泡事件的快速解决方法
2013/12/16 Javascript
深入分析escape()、encodeURI()、encodeURIComponent()的区别及示例
2014/08/04 Javascript
jquery实现的缩略图预览滑块实例
2015/06/25 Javascript
微信小程序(六):列表上拉加载下拉刷新示例
2017/01/13 Javascript
JavaScript中从setTimeout与setInterval到AJAX异步
2017/02/13 Javascript
JS变量中有var定义和无var定义的区别以及es6中let命令和const命令
2017/02/19 Javascript
JavaScript 中 apply 、call 的详解
2017/03/21 Javascript
Vue.js项目模板搭建图文教程
2017/09/20 Javascript
深入浅析Vue中mixin和extend的区别和使用场景
2019/08/01 Javascript
vue使用openlayers实现移动点动画
2020/09/24 Javascript
[06:14]《辉夜杯》外卡赛附加赛 4支战队巡礼
2015/10/23 DOTA
jupyter安装小结
2016/03/13 Python
python引入不同文件夹下的自定义模块方法
2018/10/27 Python
使用python进行拆分大文件的方法
2018/12/10 Python
python 单线程和异步协程工作方式解析
2019/09/28 Python
Python实现新型冠状病毒传播模型及预测代码实例
2020/02/05 Python
python 中不同包 类 方法 之间的调用详解
2020/03/09 Python
CSS3 对过渡(transition)进行调速以及延时
2020/10/21 HTML / CSS
HTML5 script元素async、defer异步加载使用介绍
2013/08/23 HTML / CSS
html5 http的轮询和Websocket原理
2018/10/19 HTML / CSS
印度尼西亚最大和最全面的网络商城:Blibli.com
2017/10/04 全球购物
韩国演唱会订票网站:StubHub韩国
2019/01/17 全球购物
座谈会主持词
2014/03/20 职场文书
电子信息工程专业求职信
2014/06/28 职场文书
2014普法依法治理工作总结
2014/12/18 职场文书
教师学习十八届五中全会精神心得体会
2016/01/05 职场文书
《风筝》教学反思
2016/02/23 职场文书
Win11如何启用启动修复 ? Win11执行启动修复的三种方法
2022/04/08 数码科技