小程序常用代碼


微信小程序真的是誰做誰知道,還不如用原生js

阻止事件冒泡

<view bindtap="industry">
    <view catchtap="industryCatchtap">
        industryCatchtap這個方法不需要寫,只要標注就行
    </view>
</view>

常用代碼

// 取數據,data不能不寫
this.data.xx

// 更新數據,普通的值,對象里的對象
this.setData({
   'card.industry': str,
   'industryCheckbox': arr,
   'card.industryLabel': []
})

// 如果是修改動態數組
let index = e.currentTarget.dataset.index  // 獲取數據的索引
let temp = 'goodsList[' + index +'].num'  // 獲取goodsList[index].num
this.setData({
   [temp]:this.data.goodsList[index].num + 1
})

// 從標簽上獲取data值,在標簽上綁定事件
<view bindtap="play" data-xx="xx"></view>
play:function(event){
     var xx= event.currentTarget.dataset.xx;
}

小程序沒有下拉框

// 兩個事件,兩個數據
<picker mode="multiSelector" 
        bindcolumnchange="bindMultiPickerColumnChange" 
        bindchange="bindPickerChange" 
        value="{{industry}}"
        range="{{multiArray}}">
    <view>{{industry}}</view>
</picker>

小程序的復選框
我都不知道一個復選框的控制會這么難

<view class='line-row line-row_this' bindtap="industry">
    <text>行業</text>
    <text style="flex:1;text-align:right;">{{industry}}</text>
</view>

// 每次控制顯示隱藏數據都會重新渲染
<view class='industry' wx:if="{{industryShow}}" bindtap="industry">
    <view class="industryCatchtap" catchtap="industryCatchtap">
       <checkbox-group bindchange="industryCheckboxChange">
         <view wx:for="{{multiArray}}" wx:for-item="item">
           <view class="industry1">{{item.name}}</view>
           <label class="industry2" wx:for="{{item.child}}"  wx:for-item="child">
              <checkbox value="{{child.id}}" checked="{{multiObj[child.id].checked}}"> {{child.name}} </checkbox>
          </label>
        </view>
      </checkbox-group>
    </view>
</view>
data:{
    // 接口返回值
    industry: "前端,后端",
    // 接口返回值
    industryArr: ["aa", "dd"],
    industryShow: false,
    multiObj: {},
    // 接口返回值
    multiArray: [{
      name: "it",
      child: [{ name: "前端", id: "aa" }, { name: "后端", id: "bb" }],
    }, {
      name: "it2",
      child: [{ name: "前端", id: "cc" }, { name: "后端", id: "dd" }],
    }]
},
// 接口的數據處理,把內容轉成帶有checked
dataFilter() {
    var arr = this.data.multiArray
    var obj = {}
    arr.map((x) => {
      x.child.map((y) => {
        console.log(this.data.card)
        if (this.data.industryArr.indexOf(y.id) !== -1) {
          obj[y.id] = Object.assign(y, { checked: true })
        } else {
          obj[y.id] = Object.assign(y, { checked: false })
        }
      })
    })
    this.setData({
      multiObj: obj
    })
},
industry() {
    this.setData({
      industryShow: !this.data.industryShow
    })
},
industryCheckboxChange(x) {
    var arr = x.detail.value;
    var obj = {}
    var arr2 = []
    var industry = ""
    for (var i in this.data.multiObj) {
      if (arr.indexOf(i) !== -1) {
        obj['multiObj.' + i + '.checked'] = true
        arr2.push(this.data.multiObj[i].name);
      } else {
        obj['multiObj.' + i + '.checked'] = false
      }
    }
    obj.industryArr = arr;
    obj.industry = arr2.join(",");
    this.setData(obj)
}
/*修改下默認樣式,還有一種寫法就是把checkbox隱藏了,通過checked的值增加class  */
/*checkbox 整體大小  */
checkbox {
  width: 240rpx;
  height: 90rpx;
}
/*checkbox 選項框大小  */
checkbox .wx-checkbox-input {
  width: 50rpx;
  height: 50rpx;
}
/*checkbox選中后樣式  */
checkbox .wx-checkbox-input.wx-checkbox-input-checked {
  background: #FF525C;
}
/*checkbox選中后圖標樣式  */
checkbox .wx-checkbox-input.wx-checkbox-input-checked::before {
  width: 28rpx;
  height: 28rpx;
  line-height: 28rpx;
  text-align: center;
  font-size: 22rpx;
  color: #fff;
  background: transparent;
  transform: translate(-50%, -50%) scale(1);
  -webkit-transform: translate(-50%, -50%) scale(1);
}

授權

//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'
                    })
                }
            }
        })
    }
})

table切換

<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
                });
            }
        })
    },
})

封裝一個組件

// 先在app.json里聲明組件
"pages": [
    "components/Dialog/Dialog"
],

// 在組件的json里配置
{
  "component": true,
  "usingComponents": {}
}

// wxml
<view class='wx_dialog_container' hidden="{{!isShow}}">
    <view class='wx-mask'></view>
    <view class='wx-dialog'>
        <view class='wx-dialog-title'>{{ title }}</view>
        <view class='wx-dialog-content'>{{ content }}</view>
        <view class='wx-dialog-footer'>
          <view class='wx-dialog-btn' catchtap='_cancelEvent'>{{ cancelText }}</view>
        </view>
    </view>
</view>

// js文件
Component({
  options: {
    multipleSlots: true // 在組件定義時的選項中啟用多slot支持
  },
  properties: {
    // props
  },
  data: {
    isShow: false,  // 彈窗顯示控制
    title:"",
    content:"",
    cancelText:"確認"
  },
  methods: {
    //隱藏彈框
    hideDialog() {
      this.setData({
        isShow: !this.data.isShow
      })
    },
    //展示彈框
    showDialog(obj) {
      this.setData({
        isShow: !this.data.isShow,
        title: obj.title || "標題",
        content: obj.content || "內容"
      })
    },
    /*
    * 內部私有方法建議以下划線開頭
    * triggerEvent 用於觸發事件
    */
    _cancelEvent() {
      //觸發取消回調
      this.triggerEvent("cancelEvent")
    }
  }
})

// 使用
// 在需要的page里的json里配置
{
  "navigationBarTitleText": "title",
  "usingComponents": {
    "dialog": "/components/Dialog/Dialog"
  }
}

// wxml 自定義組件標簽
<dialog id='dialog' bind:cancelEvent="_cancelEvent" ></dialog>

// js
onLoad: function (options) {
  //獲得dialog組件
  this.dialog = this.selectComponent("#dialog");
},
xx:function(){
  // 調用顯示,傳參
  this.dialog.showDialog({
     title:'提示',
     content:"pdt自定義"
   });
},
_cancelEvent() {
    // 點擊取消時,隱藏
    this.dialog.hideDialog();
},


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM