零基础研发微信小程序遇到的坑总结(持续更新)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010960265/article/details/86592253


零基础独立研发小程序遇到的坑及解决总结


1、小程序在Mac导入时打不开?

解决:目录结构里面有中文目录导致的


2、scroll-view列表中item点击事件设置

.wxml添加:

<scroll-view scroll-y = "{{true}}" style="height:{{windowHeight}}px" bindscrolltoupper="upper" bindscrolltolower="lower">
<block wx:for = "{{newslist}}">
<view style='width:100%' bindtap='clickitem' data-index="{{index}}">
<image src='{{item.newsimg}}' style='width:100px;height:100px;overflow:hidden;display:inline-block;float:left'></image>
<view style='float:left;width:250px'>
<text style='display:block'>title   :{{item.newstitle}}</text>
<text style='display:block'>author  :{{item.newsauthor}}</text>
<text style='display:block'>time    :{{item.newstime}}</text>
</view>
<view style='clear:both;display:block;height:10px;background-color:white'/>
</view>
</block>

</scroll-view>

.js添加:

var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    windowHeight:100,
    newslist:[
      {newstitle:"title1",
        newsimg: "https://ss0.baidu.com/73x1bjeh1BF3odCf/it/u=2839142893,408396789&fm=85&s=72B9616CAEE5A37650E7B08B0200E08A",
        newsauthor:"zuozhe1",
        newstime:"newstime1"},
      {
        newstitle: "title2",
        newsimg: "https://ss0.baidu.com/73x1bjeh1BF3odCf/it/u=2839142893,408396789&fm=85&s=72B9616CAEE5A37650E7B08B0200E08A",
        newsauthor: "zuozhe2",
        newstime: "newstime2"
      }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    //设置scroll-view高度
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          windowHeight: res.windowHeight
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  upper:function(){
    console.log("======uppperupper========");
  },
  lower:function(e){
    console.log("========lowerlower============");
  },
  clickitem:function(e){
    var position = e.currentTarget.dataset.index;
    console.log("================"+position);
  }

})

3、小程序页面之间的跳转

3.1 wx.navigateTo({}) ,保留当前页面,跳转到应用内的某个页面,使用 wx.navigateBack 可以返回;

示例:

wx.navigateTo({
	url:'../test/test?id=1&page=4',  //跳转页面的路径,可带参数 ?隔开,不同参数用 & 分隔;相对路径,不需要.wxml后缀
	success:function(){}        //成功后的回调;
	fail:function(){}          //失败后的回调;    
	complete:function(){}      //结束后的回调(成功,失败都会执行)
})

// 传递的参数在接收页面onLoad()函数中得到值:option.id就可以得到了
 onLoad: function (option) {
  console.log(option)//可以打印一下option看查看参数
  this.setData({
  id:option.id,
 });
3.2 wx.redirectTo() , 关闭当前页面,跳转到非tabBar的某个页面,
3.3. 使用组件 示例: 点击跳转
3.4. wx.switchTab ,跳转到tabBar的某个页面,
wx.switchTab({
      url: '../taste/index',   //注意switchTab只能跳转到带有tab的页面,不能跳转到不带tab的页面
    })

4、小程序 swiper(或者 scroll-view) 隐藏滚动条

在.wxss 添加:

// scroll-view隐藏滚动条方法
::-webkit-scrollbar{
width: 0;
height: 0;
color: transparent;
}

// swiper隐藏滚动条方法
.tab-swiper ::-webkit-scrollbar {
  width: 0;
  height: 0;
  color: transparent;
}

5、微信小程序下拉刷新/上拉加载更多实现

查看文档,在用page()函数注册页面的时候有这样的两个对象参数用户判断用户在最顶部下拉和到达最底部,在小程序里,用户顶部下拉是默认禁止的,我们需要把他设置为启用,在app.json中的设置对所有页面有效,在单独页面设置则对当前页面有效;
在这里插入图片描述

看一下.json文件,添加:

"enablePullDownRefresh": true,

注意:这里的true是布尔型而不是字符;
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190122172735905.png

每个页面生成的时候已经默认为我们设置了前面提到的onPullDownRefresh函数和onReachBottom函数

扫描二维码关注公众号,回复: 5354955 查看本文章

直接上代码:

page为全局变量,用在在后面的加载请求:

下拉刷新:

 // 下拉刷新
  onPullDownRefresh: function () {
    // 显示顶部刷新图标
    wx.showNavigationBarLoading();
    var that = this;
    wx.request({
      url: 'https://xxx/?page=0',
      method: "GET",
      header: {
        'content-type': 'application/text'
      },
      success: function (res) {
        that.setData({
          moment: res.data.data
        });
        // 设置数组元素
        that.setData({
          moment: that.data.moment
        });
        console.log(that.data.moment);
        // 隐藏导航栏加载框
        wx.hideNavigationBarLoading();
        // 停止下拉动作
        wx.stopPullDownRefresh();
      }
    })
  },

上拉加载更多:

/**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    // 显示加载图标
    wx.showLoading({
      title: '玩命加载中',
    })
    // 页数+1
    page = page + 1;
    wx.request({
      url: 'https://xxx/?page=' + page,
      method: "GET",
      // 请求头部
      header: {
        'content-type': 'application/text'
      },
      success: function (res) {
        // 回调函数
        var moment_list = that.data.moment;
 
        for (var i = 0; i < res.data.data.length; i++) {
          moment_list.push(res.data.data[i]);
        }
        // 设置数据
        that.setData({
          moment: that.data.moment
        })
        // 隐藏加载框
        wx.hideLoading();
      }
    })
 
  },

6、微信小程序 — model弹框

model弹框:在屏幕中间弹出,让你进行选择:

效果:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190122173335732.png

代码:

<button type="primary" bindtap="btnclick">按钮</button>
<modal title="标题" confirm-text="确认" cancel-text="取消" hidden="onOff" bindconfirm="modalConfirm" bindcancel="modalCancel">
这里是会话内容
</modal>

page.js:

//获取应用实例
const app = getApp()
Page({
  data: {
      onOff:true 
  }, 
  btnclick:function(){
      var onOff = this.data.onOff;
      this.setData({onOff:!onOff});
  }
})

还可以使用JS:

btnclick:function(){
    wx.showModal({
        title: '提示',
        content: '这是一个模态弹窗',
        success: function(res) {
           if (res.confirm) {
              console.log('用户点击确定')
           } else if (res.cancel) {
              console.log('用户点击取消')
           }
        }
    })
}

具体的参数:

title:提示的标题;

content:提示的内容;

showCancel :是否显示取消按钮,默认是 false

canceText:取消按钮的文字,默认是 “取消”

canceColor:取消按钮的文字颜色,默认是 #000

confirmText:确定按钮的文字。默认是 确定

confirmColor:确定按钮的文字颜色。默认是 “#3CC5IF”

success:接口调用成功的回调函数。返回 res.confirm ==1时,表示用户点击。

fail:接口调用失败的回调函数。

complete:接口调用结束的回调函数(调用成功或者失败都会执行)


7、小程序 同一个字符串不同颜色设置

如下:

<view>
	<text >{{value1}}</text> <text style="color:#0076ff">{{keyword}}</text>
</view>

8、微信小程序 position: absolute位置错乱问题

界面效果:
在这里插入图片描述

碰到的问题: 子布局设置position: absolute,
在这里插入图片描述

解决办法: 子布局的父布局一定要设置position: relative。

如果父元素 不加这个属性 就会再往外面一层,如果外面一层还未找到relative就继续向外 最终相对于body。 找到哪一层有relative,就相对于那个父布局。

父布局:

position: relative;
  width: 210rpx;
  height: 100rpx;

子布局:

position: absolute;
  bottom: 0;
  right: 0;
  width: 50rpx;
  height: 50rpx;

注意:子布局使用position: absolute,父布局一定要设置position: relative;


9、微信小程序设置圆形图片

效果如下:
在这里插入图片描述

home.wxss

.profile{
  width: 50rpx;
  height: 50rpx;
  border: 0 solid #ff0000;
  border-radius: 100rpx;
  background-color: #f10b2e;
}

home.wxml

      <image src="/res/icon_tab_fighting.png" class="profile"></image>

10、当点击分享按钮时会触发到父级的 bindtap 事件,该如何解决这个问题呢?

解决办法:只需要将按钮事件 bindtap 换成 catchtap 事件即可完美解决。


11、微信小程序去除button边框

button::after{
	border: none;
}

12、小程序隐藏元素的几种方式

有些时候我们需要对一些元素进行隐藏和显示控制,这时我们要用到一些属性。

①使用hidden属性,然后在页面的js文件中通过修改hidden值来控制,

<view hidden="true">每个组件都有的hidden属性</view>

<view hidden='false'>每个组件都有的hidden属性</view>
<view hidden="{{hiddenn}}">每个组件都有的hidden属性</view>

②使用display属性,

<view style="display:none">每个组件都有的display属性</view>//元素不显示
<view style="display:block">每个组件都有的display属性</view>//元素显示
<view hidden="{{'adfad'=='adf'}}">每个组件都有的dy属性</view>//当然在{{}}表达式中也可以使用一些简单的运算。

③使用wx:if指令。

<view wx:if="{{3>2}}">我是wx:if</view>

④使用opacity属性

<view style="opacity:{{opacity}}">我是opacity属性</view>

13、小程序固定底部、居中的悬浮按钮

.wxml:

<view class="add-wrap"hover-class="plus-hover">
  <image src="/assets/plus_new.png"></image>
</view>

.wxss:

add-wrap {
  position:fixed;
  bottom:0;
  display:flex;
  width:100%;
  justify-content:center;
}
.add-wrap image {
  width:64px;
  height:64px;
}

效果:
在这里插入图片描述

14、微信小程序开发常用技巧 —— 修改page背景色

其实很简单,在对应的wxss文件中对page进行设置就可以达到我们想要的效果。
代码如下:

.wxss添加:

page{
  background-color: lightcyan;
}

15、微信小程序计算input框输入的长度以及绑定输入事件

15.1 input框输入的长度计算

如图:
在这里插入图片描述

wxml 和 wxss只是布局 看js逻辑

<view class='input'>
  <text class='input-left'>标题</text>
  <input name='' value='' placeholder='请输入' bindinput='length'></input>
  <text class='input-right'>{{length}}/30</text>
</view>
.input{
  width: 100%;
  border-bottom: 1rpx solid #efefef;
  height: 88rpx;
  border-top: 1rpx solid #efefef;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
 
.input-left{
  margin-left: 25rpx;
  font-size: 30rpx;
}
 
.input-right{
  margin-right: 25rpx;
  font-size: 30rpx;
}
 
input{
  font-size: 30rpx;
  width: 500rpx;
}

.js

Page({
 
  /**
   * 页面的初始数据
   */
  data: {
    length: 0
  },
  length(e) {
    let length = e.detail.value.length
    // console.log(length)
    this.setData({
      length: length
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
 
  },
 
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
 
  },
 
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
 
  },
 
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
 
  },
 
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
 
  },
 
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
 
  },
 
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
 
  },
 
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
 
  }
})
15.2 绑定事件

表单提交在前端界面无处不在,我们需要获取值,监听输入的值,提交表单的数据

表单界面,css样式我就不贴出来了,我主要说明的是js部分的使用

<view class="container" wx:if="{{hasAuthority}}">
    <view class="title">
        绑定你的手机号
    </view>
    <view class="main">
        <view class="small-title">
            手机号
        </view>
        <input type="number" placeholder="请输入手机号" class="inp-holder" maxlength="11" bindinput="getPhone" />
         <view class="lineView"></view>
    </view>
    <view class="main">
        <view class="small-title">
            <text>验证码</text>
            <text class="code" bindtap="getMessage">{{getCode}}</text>
        </view>
        <input type="number" placeholder="请输入验证码" class="inp-holder" maxlength="6" bindinput="getCode" />
        <view class="lineView"></view>
    </view>
    <button class="login-btn" type="default" bindtap="defaultTap" hover-class="defaultTap">登录</button>
</view>

js代码:

我们只给出获取手机号取值的方式,注意你每输入一个数字getPhone的事件就会执行一次,

e.detail.value 就是控件里面当前的值,然后每个控制都取到值,setData后,就可以提交数据给服务端了

  // 拿到手机号
    getPhone: function (e) {
        var val = e.detail.value;
        this.setData({
            telphone: val
        });
    },

16、微信小程序 如何获取列表item中按钮的index???

其实很简单,只要设置 button 的 data-index 属性就可以了,代码如下:

.wxml 代码:

<scroll-view class="scroll-views" scroll-y="true" scroll-x="false">
      <view class="orderListDetails" wx:for="{{allOrder}}" wx:key=" " bindtap='clickItemAction' data-index='{{index}}'>
          <view class="orderList_top_sub_title">下单时间 {{item.time}}
          </view>
          <text class="orderList_status">{{item.status}}</text>
          <view class="productImg">
            <image src="{{item.url}}" background-size="cover"></image>
          </view>
          <view class="productInfo">
            <view class="orderList_goodsName">{{item.name}}</view>
            <text class="orderList_price">¥{{item.price}}</text>
            <text class="orderList_number">x{{item.number}}</text>
          </view>
          <view class='orderList_line'></view>
          <view class='orderList_bottom_btns'>
            <view class="orderList_bottom_number">共{{item.number}}件商品 实付 <text style='color:#E22929;font-size:36rpx;font-family:DIN-Bold;font-weight:bold;line-height:36rpx;'>¥{{item.price}}</text></view>
            <button class='orderList_bottom_cancelBtn' catchtap='cancelOrderAction' hidden='{{item.orderStatus==2 | item.orderStatus==3}}' data-index='{{index}}'>取消订单</button>
            <button class='orderList_bottom_payBtn' catchtap='goPayAction' hidden='{{item.orderStatus==2}}' data-index='{{index}}'>{{item.orderStatus==1?'去支付':'提货凭证'}}</button>
          </view>
        </view>
    </scroll-view>

.js 添加如下代码:

/**全部/待付款
   * 取消订单
   */
  cancelOrderAction: function (e) {

    var that = this
    var tapItemIndex = e.currentTarget.dataset.index
    console.log('取消订单',tapItemIndex)
  },

  /**全部/待付款
   * 去支付
   */
  goPayAction: function (e) {

    var that = this
    var tapItemIndex = e.currentTarget.dataset.index
    }

17、微信小程序多层嵌套循环,二级数组遍历

小程序中的遍历循环类似于angularJS的遍历。

二级数组遍历有一个坑。二级遍历wx:for循环的时候,需要注意。(代码如下)

JS代码:

data: {
        groups: [
            [
                {
                    title: '狼图腾',
                    cover: '../../img/mineBG.png'
                },
                 {
                    title: '狼图腾',
                    cover: '../../img/mineBG.png'
                },
            ],
            [
                {
                    title: '狼图腾',
                    cover: '../../img/mineBG.png'
                },
                
            ],
            [
                {
                    title: '狼图腾',
                    cover: '../../img/mineBG.png'
                },
               
            ]
        ],
    },

遍历出不同的数组,然后渲染不同组的cell

<!--一共三组-->
<view class="group" wx:for="{{groups}}"  wx:for-index="groupindex">
 
  <!--组头-->
  <view class="group-header">
    <view class="group-header-left">{{}}</view>
    <view class="group-header-right">{{}}</view>
  </view>
<br><br><br>MARK:<br>二级循环的时候,wx:for="item",这种写法是错误的。<br><br>
  <!--cell-->
  <view class="group-cell" wx:for="{{groups[groupindex]}}" wx:for-item="cell" wx:for-index="cellindex">
    <!--<image class='group-cell-image' src="{{item.cover}}"></image>-->
    <image class='group-cell-image' src="../../img/mineBG.png"></image>
    <view class='group-cell-title'>title{{cell.title}}</view>
  </view>
 
  <!--footer-->
  <view class="group-footer">{{group.footer}}</view>
</view>

猜你喜欢

转载自blog.csdn.net/u010960265/article/details/86592253
今日推荐