微信小程序

######

#小程序基本写法

size={

   一般用iphone6大小尺寸375px  而设计图一般给750rpm

    px是物理分辨率,和屏幕尺寸没有关系

    ip6下 1px=1rpx

    使用rpx,小程序会自动进行转换,而px不会

 

  1px=2rpx #一般用rpx

}

#最终上传代码不能超过1M

###########基本结构###########

##单个页面##

.js

.wxml

.wxss


 

#获取用户信息

  wx.login({#wx.login 弹出框让用户授权,是登录,返回code给服务器,服务器调用后会,微信又会返回openid,还有一个sessionkey,给服务器(code只能使用一次)

    success: res => {#这里我们获取code值去取openid和session_key,这里我们利用EasyWechat类获取,此时服务器并未获取用户信息

      this.get('/Miniapps/session', { code: res.code }, res => {

        console.log(res.data.openid)

        this.setGlobal('openid', res.data.openid);

        this.getUserInfo()

      }

      )

    }

  })

  getUserInfo(){

      wx.getUserInfo({ #wx.getUserinfo 获取用户信息,需要用户允许,也就是会弹出框让用户授权,不管有没有登录都可以获取到信息,但是登录后可以获取到一些敏感信息

        success: res => {

          res.userInfo.openid = this.d.openid;

          this.post('/Mobile/Card/login', res.userInfo, res => {

            this.setGlobal('token', res.data.token)

            this.setGlobal('userInfo', res.data.user);

            console.log(this.d.token);

            if (this.requestReady) {

              this.requestReady(res)

            }

          })

        },

        fail: res => {

          wx.openSetting()#如果取消授权,返回这个设置,为啥用这个,个人测试发现,如果某人点入了小程序,会弹出授权框,点取消后再次进入,就不会出现了,只会出现wx.openSetting()

        }

      })

  }

 

  重点:经过测试, 如果把wx.openSetting()放在app.js onLaunch方法里,那么只会执行一次

  #如果方案需要必须关注,则可以在index或者app.js的onShow方法里定义

    onShow:function(){

      wx.showModal({

        title: '用户未授权',

        content: '如需正常使用该小程序功能,请按确定并在授权管理中选中“用户信息”,然后点按确定。最后再重新进入小程序即可正常使用。',

        showCancel: false,

        success: function (resbtn) {

          if (resbtn.confirm) {

            wx.openSetting(

 

            )

          }

        }

      })

    },


 

# 小程序生命周期#

#后台和前台

app.js里的函数:

 

onLaunch:function(){

#小程序启动时第一个运行,初始化工作

}

onShow:function(){

#刚开始第二步,小程序启动或从后台进入前台时,触发执行的操作

},

onHide:function(){

#第一次跳转到index/index时不执行,点击最右上角的原点会先执行这个函数,然后再执行当前页onHide,

#小程序从前台进入后台时,触发执行的操作

#如果重新进当前页,则会先执行App onShow方法,然后再执行当前页onShow方法

}


 

page.js里的函数:

 

onLoad: function (options) {

#页面加载时执行初始化工作(无画面)

},

onShow:function(){

#页面打开时,触发执行的操作,第一次也会执行

}

onReady:function(){

#页面初次渲染完成,页面渲染完成(有页面)

}

#上面三个是刚进一个页面执行的顺序,进路由也是,但返回除外

 

onHide:function(){

#页面隐藏时,触发执行的操作,跳转路由,则起始页会执行onHide方法

}

onUnload: function () {

#监听页面卸载

},

注意:如果一个页面点返回,那么当前页面会先执行onUnload方法,返回的那个页面,只会执行页面的onShow方法

###########不常用的方法##############

onPullDownRefresh: function () {

#监听用户下拉动作 (测试不成功)

},

 

onReachBottom: function () {

#页面上拉触底事件的处理函数

},

onShareAppMessage: function () {

  #用户点击右上角分享或者转发,当点击转发那个button,触发

}



 

App.json值

  "window": { #App里面的是全局配置,也就是其他页面默认这些,如果不一样,可以改当前页面的window配置

    "backgroundTextStyle": "light",#下拉背景字体,仅支持dark/light

    "navigationBarBackgroundColor": "#fff",#导航背景颜色

    "navigationBarTitleText": "Demo",#导航栏标题文字类容

    "navigationBarTextStyle": "black"#导航栏标题颜色,仅支持black/white

  },

    "tabBar":{ #下面的切换

    "color":"red",#颜色

    "borderStyle":"black",#字体风格

    "selectedColor":"#fff",#选中时字体颜色

    "backgroundColor":"#888888",#背景颜色

    "list":[{

      "pagePath": "pages/index/index",#页面路径

      "text":"首页"#导航栏标题文字类容

      "iconPath":"pages/omage/caa.png",#默认图形

      "selectedIconPath":"pages/omage/caa.png"#选中图形

    },{

        "pagePath": "pages/shop/shop",

        "text": "日志"

    }]

  }

 

# .js数据,赋值

  data:{

  text:''

  }

 

  this.setData({#只能这样赋值,如果this.data.text="12333",会报错

    text:'123123'

  })

 

# if条件判断

  <view wx:if="{{view=='web'}}">WEB</view>#可以用block标签包裹,不被渲染

  <view wx:elif="{{view=='APP'}}">APP</view>

  <view wx:else="{{view=='MIN'}}">{{view}}</view>

 

#事件绑定

  bindtop="add"#绑定add事件

 

#组件属性绑定

  <view id="item-{{id}}"></view>

  Page({

  data:{

    id:0

  }

  })

 

#控制属性

  <view wx:if="{{condit}}"></view>

  Page({

  data:{

    condit:true

  }

  })

#三目运算

  <view hidden="{{condit?true:false}}">Hidden</view>

 

#字符串运算

  <view>{{"hellow"+name}}</view>

  Page({

  data:{

    name:'MINA'

  }

  })

#数据路径运算

  <view>{{object.key}}{{array[0]}}</view>



 

#数组遍历

  <view wx:for="{{[zero,1,2,3,4]}}">{{index}}{{item}}</view>

#如果数组单纯是一个数字的数组,那么wx:key="this",this表示当前循环item本身

#如果对象是一个键值对,那么显示则需要{{item.key}}

#index表示索引,0,1,2

#item:表示内容,也就是那个对象

  Page({

  data:{

    zero:0

  }

  })




 

#模版引用

  比如在item.wxml中定义了一个模版

  <template name="item">

  <text>{{text}}<text>

  </template>

  如果在index.wxml中引用到了上面的模版

  <import src="item.wxml"/>#引入了这个模版

  <template is="item" data="{{text:'forbar'}}">

  <text>{{text}}<text>

  </template>


 

#微信小程序本地存储

#目前微信小程序wx.setStorage获得的缓存数据是“持久”保存的,不是“永久”,获得后就存在客户端,

#除非主动销毁或者从客户端删除该小程序。就是你在“微信—发现—小程序”列表里删除这个小程序。

  wx.setStorage({

    key: "users",

    data: "liuzhiliang"

  })#保存key值

  wx.getStorage({

    key: 'users',

    success: function (res) {

      console.log(res.data)

    }

  })#获取key值

  wx.removeStorage({

  key: 'key',

  success: function(res) {

    console.log(res.data)

  }

  })#移除指定key值

  wx.clearStorage()#清理缓存

#同步缓存,同步缓存直到同步方法处理完才能继续往下执行。

  wx.setStorageSync(KEY,DATA)

  wx.getStorageSync(KEY)

  wx.getStorageInfoSync

  wx.removeStorageSync(KEY)



 

#重定向,路由跳转

  wx.navigateTo({

      url: '',#路由跳转,原窗口不会关闭

  })

#传参数 data-carid={{item.ID}}

wx.navigateTo({

  url: '/pages/cardetail/cardetail?id=' + e.currentTarget.dataset.carid

})

 

#/pages/cardetail/cardetail里的

  onLoad: function (options) {

   console.log(options.ID);#接收传过来的参数

  },


 

  wx.redirectTo({

    url: '',#重定向,原窗口会覆盖

  })




 

#input

  <input type="text" class="search-icon" placeholder="请输入要搜索的内容" bindinput="searchNameInput"/>

  searchNameInput: function (e) {

    var that = this;

    console.log(e.detail.value)#同步输入的值

    that.setData({

      inputValue: e.detail.value

    })

  },


 

#请求,上传,下载

  wx.request:#发起网络请求

  wx.uploadFile:#上传文件

  wx.downloadFile:#下载文件

 

#getCurrentPages()

#获取实例,也就是总共有多少路由

  getCurrentPages().length,可以通过这个数量,来判断几成路由

 

#target(重点)

#触发事件的一些属性值的集合

  <view data-alp-beta="2" data-beta="3" bindtap="bindview"></view>

  bindview:function(event){

  console.log(event.target.dataset.beta);#为3

  console.log(event.target.dataset.alpBeta);#为2,-要转化为大写

  }


 

#导入样式

  @import "common.wxss"

#支持的选择器

  .class

#id

  element

  ::after

  ::before


 

#视图容器组件

 

##view:#相当于css中的div元素

  <view class="viewclass"></view>

 

##scroll-view:#可滚动视图区域组件

  <scroll-view scroll-x="true"><scroll-view/>

#参数

  scroll-x :Boolean#允许横向滚动

  scroll-y :Boolean#允许纵向滚动

  upper-threshold :Number 默认50 #距离顶部/左边多远时(单位:px),触发scrolltoupper事件

  lower-threshold :Number 默认50 #距离顶部/左边多远时(单位:px),触发scrolltolower事件

  scroll-top :Number #设置竖向滚动条位置

  scroll-left :Number #设置横向滚动条位置

  scroll-into-view String #值应为某子元素的id,当滚动到此处,元素顶部对其滚动区域顶部

  bindscrolltoupper #事件,滚动到顶部/左边,会触发scrolltoupper事件

  bindscrolltolower#事件,滚动到底部/右边,会触发scrolltolower事件

  bindscroll#触发时滚动

 

##swiper滑块视图组件

#swiper-item为滑块项组件,仅可放置在<swiper>中,宽高自动设置成100%;

  <swiper autoplay="autoplay" circular="true" current="{{Current}}" duration="{{duration}}" interval="{{interval}}" indicator-dots="{{indent}}">#indent为true或者false,是否显示圆点

  <block wx:for="{{dots}}">

  <swiper-item>

  <image src="{{item}}" width="355" height="150"/>

  </swiper-item>

  </block>

  </swiper>

  autoplay:false,#是否自动切换滚动

  interval:5000,#自动切换时间间隔

  duration:1000#滑动动画时长

  Current:2#表示刚进入页面从index为2开始轮播

  circular:#无缝滚动,或者无缝滑动

#bindchange事件函数,current改变时会触发change事件

##测试链接

  dots:[

  'http://yc.wzjo2o.com/uploads/1/201712/20171220091639_429.jpg',

  'http://yc.wzjo2o.com/uploads/1/201712/20171220092020_645.jpg',

  'http://yc.wzjo2o.com/uploads/1/201712/20171220091658_689.jpg',

  ]

 

#公告类型滚动

   <view class="hot_news_box">

      <view class="hot_news">

      <view class="hot_title">汽车头条:</view>

        <image class="gonggao_img"  src="../../img/xiaoxigongbu.png" />

      </view>

      <swiper class="swiper_container" vertical="true" autoplay="true" circular="true" interval="2000">

        <block wx:for="{{msgList}}">

          <navigator url="/pages/index/index" open-type="navigate">

            <swiper-item>

              <view class="swiper_item ellipsis"><span style="font-size:20rpx;vertical-align:middle;color:#ff4d00;margin-right:7rpx;">●</span>{{item.title}}</view>

            </swiper-item>

            </navigator>

        </block>

      </swiper>

      </view>

data:

msgList: [

  { url: "url", title: "4S店不再一家独大" },

  { url: "url", title: "按国补50%补助 海南发布新能源补贴政策" },

  { url: "url", title: "董明珠造车再受挫 珠海银隆IPO辅导终止" },

  { url: "url", title: "按国补50%补贴 广州发布新能源补贴政策" },

  ]

css

.swiper_container{

  width:74%;

 height:50rpx;

 padding-top:10rpx;

}

.hot_news_box{

  display: flex;

  align-items: center;

  justify-content: space-between;

  padding:20rpx 30rpx 0 30rpx;

  background-color:#fff;

}

.hot_news{

  display: flex;

  justify-content: space-around;

  align-items: center;

  width:25%;

}

.gonggao_img{

  width:40rpx;

  height:35rpx;

 

}

.hot_title{

  font-size:29rpx;

  color:#ff4d00;

}


 

#基础类容组件

 

#icon

<icon type="success" size="24" color="#f0f0f0"/>

  <icon type="success" size="23" color="背景颜色"/>#成功图标

  info#蓝色感叹号,注意

  warn#红色感叹号,注意

  success_no_circle#对 勾

  success_no_circle#对 勾

  waiting#等待

  cancel#红色×

  download#下载图标

  search#搜索

  clear#灰色×

 

#button 表单按钮组件

  <button type=""></button>

  size:default,mini

  type:primary,default,warn

  plain:#是否镂空,背景色透明

  disabled:#是否禁用

  loading:#名称是否带loading图标

  form-type:#有效值包括submit.reset

  hover-class:#指定按钮按下去的样式类


 

#text 文本组件

它支持转义符"\"

 

#progress 进度条组件

progress percent="20" color="pink" show-info stroke-width="12" active/>

#percent,百分比0~100

#show-info 在进度条右侧显示20%的文字

#stroke-width:进度条线的宽度

#color:进度条颜色

#active:进度条从左到右的动画


 

#选择器组件

#checkbox

  <checkbox-group bindchange="checkboxChange">

  <label>

  <checkbox value="{{item.name}}" checked="{{item.checked}}"/>{{item.value}}

  </label>

  </checkbox-group> #只要选中改变,会触发bindchange事件

 

#swith

  <switch checked name="swith" bindchange="change"/>#swith标签

  function(e){

  e.detail.value#选择的值,true或者是false

  }

 

#输入框input

  <input />

  value#输入框的值

  type#input类型,text,number,idcard,digit,time,date

  password#是否是密码类型

  placeholder#输入框为空时占位符

  disabled#是否禁用

  maxlength#最大输入数

  auto-focus#自动聚焦,拉起键盘

  bindchange#失去焦点时触发

 

#textarea 多行输入框,和input类型差不多

  auto-height#是否自动增高

  bindblur#失去焦点触发

 

#单选

  <radio-group bindchange="radiochange">

  <label wx:for="{{labems}}">

  <radio value="{{item.name}}" checked="item.checked">{{item.value}}</radio>

  </label>

  </radio-group>

  data:

  labems:[

  {name: 'USA', value: '美国'},

  {name: 'CHINA', value: '中国', checked: 'true' },

  {name: 'JX', value: '南昌'},

  {name: 'HF', value: '合肥'},

  ]

  radiochange:function(e){#有时候不知道可以输出e看看

    console.log(e.detail.value);

  }

 

#多选


 

#pick下拉选择

  <picker bindchange='bindpicker' value="{{index}}" range="{{array}}">

  <view>

  当前选择:{{array[index]}}

  </view>

  </picker>

data:

  index:0,

  array:['美国','中国','日本'],

事件:

  bindpicker:function(e){

    this.setData({

      index:e.detail.value

    })

  },

 

#年月日

    <picker mode="date" bindchange='bindDate' value="{{date}}" start="1999-09-01" end="2017-09-01">

    <view>

    当前选择:{{date}}

    </view>

    </picker>

  data:

  date:'2011-09-01'

  事件:

  bindDate:function(e){

    this.setData({

    date: e.detail.value

    })

  },

 

#时间

    <picker mode="time" bindchange='bindDate' value="{{time}}" start="09:01" end="21:09">

      <view>

      当前选择:{{time}}

      </view>

    </picker>

    data:

    time:'12:01'

    事件

      bindDate:function(e){

      this.setData({

      time: e.detail.value

      })

    },

 

#弹窗

    <button type="default" bindtap="sheep">弹窗</button>

    <action-sheet hidden="{{Hidden}}" bindchange="sheetchange">#点遮罩触发bindchange事件

    <view>我是弹窗</view>

    <action-sheet-cancel>取消</action-sheet-cancel>

    </action-sheet>

    data:

    Hidden:true

    事件:

    sheep:function(e){

    this.setData({

      Hidden: !this.data.Hidden

    })

    },

    sheetchange:function(e){

    this.setData({

      Hidden: !this.data.Hidden

    })

    },

 

#常用的对话框,有取消或者确认

    <modal title="标题" confim-text="confim" cancel-text="cancel" hidden="{{modalHidden}}"

    bindconfirm="modalchange" bindcancel="modalchange"> #bindconfirm,点确定触发,modalchange,取消触发

    对话类容

    </modal>

    <view>

      <button type="default" bindtap="modaltap">单击弹出modal</button>

    </view>

    data:

    modalHidden: true,

    事件

      modaltap: function (e) {

        this.setData({

          modalHidden: false#打开

        })

      },

    #无取消,只有确定

    <modal no-cancel hidden="{{modalHidden}}" bindconfirm="modalchange">

    对话类容

    </modal>


 

#toast提示,提示马上消失

  wx.showToast({

      title: '成功',

      icon: 'succes',#只支持'succes'或者'loading'

      duration: 1000,

      mask: true

    })



 

#页面导航组件

<navigator url="../index/index">点击</navigator>#相当于a标签 对应wx.navigatorTo

<navigator redirect url="../index/index">点击</navigator>#相当于a标签 对应wx.redirectTo

<navigator url="../index/index" open-type="switchTab">切换到首页Tab</navigator>#switchTab,只能跳转到Tabbar路径地址

 

#视频标签

<video src="" autoplay="true" controls style="width:200px;height:200px;"/>

https://www.2cto.com/kf/201803/730740.html

#objectFit|String|contain|当视频大小与 video 容器大小不一致时,视频的表现形式。contain:包含,fill:填充,cover:覆盖

#autoplay自动播放

#bindplay(事件)当开始/继续播放时触发

#bindpause(事件)当暂停播放时触发

#bindended(事件)当播放到末尾时触发ended事件

#binderror(事件)发生错误时触发

 

#可以控制它的播放和暂停

  onLoad: function (options) {

this.videoContext = wx.createVideoContext('video')#id="video"

  },

this.videoContext.pause();#暂停

this.videoContext.play();#播放


 

#网络API

    wx.request#用于发起https请求

    wx.request({

      url:'test.php',

      data:{ #携带的参数

        x:'',

        y:''

      },

      header:{

        'Content-Type':'application/json'

      },

      success:function(res){#接收返回的值

        console(res.data)

      },

      fail:function(){

 

      }

    })

 

#本地相册选择图片或使用照相机拍照wx.chooseImage()

  //添加照片步骤

  var _this = this

  wx.chooseImage({

    count: 1, // 默认9

    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有

    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有

    success: function (res) {

        // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片

        var tempFilePaths = res.tempFilePaths

        // var index = e.currentTarget.dataset.aid

        var index = _this.data.addImageAid

        _this.uploadMultiImg(tempFilePaths, index, 0)

    },

    fail: function () {

        console.log('图片失败')

        _this.setData({

            deleteContentType: 'image'

        })

        _this.deleteContent()

    }

  })

 

  uploadMultiImg(paths, index, 0){#上传到服务器

      var _this = this

          wx.uploadFile({

              url: app.host() + '/Mobile/Photos/upload', #仅为示例,非真实的接口地址,请求的php

              filePath: paths[i],

              name: 'file',

              formData: {

                  'photo': 'test'

              },

              header: {

                  'XPS-Token': app.d.token

              },

              success: function (res) {

                  if (i < paths.length - 1) {

                      i++;

                      _this.data.article[index].images.push(JSON.parse(res.data).data)

                      return _this.uploadMultiImg(paths, index, i)

                  } else {

                      _this.data.article[index].images.push(JSON.parse(res.data).data)

                      _this.setData({article: _this.data.article})

                      return true;

                  }

              },

              fail: function (res) {

                  _this.uploadMultiImg(paths, index, i)

              }

          })

  }

 

  #视频上传步骤

    wx.chooseVideo({

    sourceType: ['album', 'camera'],

    maxDuration: 60,

    compressed: true,

    success: function (res) {

    var tempFilePath = res.tempFilePath#上传视频的临时路径

    wx.uploadFile({#都用此方法上传到服务器

      url: app.host() + '/Mobile/Video/upload', //仅为示例,非真实的接口地址

      filePath: tempFilePath,

      name: 'file',

      formData: {

          'vido': 'test'

      },

      header: {

          'XPS-Token': app.d.token

      },

      success: function (res) {

          console.log(res)

          var result = JSON.parse(res.data).data

          console.log(11111)

          console.log(result)

          _this.data.article[index].fdcVideo = result.video

          _this.data.article[index].fdcVideoCover = result.cover

          app.msg('上传成功')

          _this.setData({article: _this.data.article})

      },

      fail: function () {

          app.msg('上传失败')

      }

    })

    },

    })

  #录音上传步骤



 

  #获取用户设备信息

wx.getSystemInfo({

  success: (res => {

    console.log(res);#会出来很多信息

    if (res.brand == "devtools") {#指的是开发环境

      devtool = true

    }

  })

})

 

##客服信息

<contact-button size="24"  type="default-light" class='pos1' session-from="weapp"></contact-button>

#用这个组件,但是腾讯很坑,样式不能改,改完也是很小,所以需要重复上面代码很多次,才容易调起来

 

.pos1{

  position:absolute;

  opacity:0;

}

 

#获取网络状态

wx.getNetworkType({

 

success: function(res) {

 

that.setData({

 

netWorkType:res.networkType

 

})

 

#img图片放大

data-src="{{item}}" data-list="{{CarInfo.imglist}}"

#事件

wx.previewImage({

  current: e.currentTarget.dataset.src,#当前图片的src

  urls:e.currentTarget.dataset.list#图片总链接

})



 

#小程序里的scroll,返回顶部或者返回某个元素的写法

<scroll-view class="bigWrap" scroll-y="true" scroll-top="{{scrollTop}}"

 bindscroll="scroll" bindscrolltolower= "scrolltolower" scroll-into-view="{{View}}"

 style="position: absolute; left: 0; top:0; bottom: 0; right: 0;">#这里没设置height

 </scroll>

 data:

View:"",  #scroll-into-view元素id,会跳到指定id

scrollTop: 0#起始位置

this.setData({#返回顶部

  scrollTop: 0

})

 

#计算某元素在不同分辨率的高度

  var query = wx.createSelectorQuery()

  query.select("#Carcom").boundingClientRect()

  query.selectViewport().scrollOffset()

  query.exec(function (res) {

    this.setData({

      Daheight: res[0].top  #Daheight就是元素Carcom元素到顶部的距离

    })

  })

#





 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值