微信小程序知識記錄(有時間會更新其他)

recored

後續會不定期更新其他,寫的不好,歡迎大神前來指教。

修改data中屬性對象賦值

第一種:

data: {
	baseInfo:{
		name: '小小個',
		age: 19
	},
}

//修改data裏的數組或對象的屬性
this.setData({
	'baseInfo.age': 24
})

第二種:

根據條件修改某個屬性值, 需要先把屬性轉換成字符串,再用中括號括起來

	//根據條件修改某個屬性值
var radioChecked = "lavipeditumData[" + i + "].radioChecked"; //需要修改的屬性
that.setData({
    [radioChecked]: true, //賦值
})


//demo: 
// 1. 遍歷給數組中每個對象添加某個值
for (var i = 0; i < tempMealData.length; i++) {
    tempMealData[i]["radioChecked"] = false;
}
this.setData({
    lavipeditumData: tempMealData, //{ radioChecked: false }
})

// 2. 改變屬性值
that.data.lavipeditumData.forEach((item, i) => {
    if (item.key == that.data.ticketFreeTime) {
        var radioChecked = "lavipeditumData[" + i + "].radioChecked";
        that.setData({
            [radioChecked]: true, //{ radioChecked: true}
        })
        
		//[`lavipeditumData[${i}].radioChecked`]: true  es6語法
    }
})

微信小程序解析富文本數據

可通過 rich-text組件 解析富文本數據。 nodes節點類型區分

 <rich-text nodes="{{item.content}}"></rich-text>

處理富文本圖片問題

默認情況下展示圖片原來的尺寸,這裏獲取到數據後處理一下。

// 替換匹配所有img,設置樣式
list[i].content = list[i].content.replace(/\<img/gi, '<img style="width:100%;height:auto" ')

完整代碼

wxml

<view wx:for="{{helpInfoData}}" wx:key="*this">   
    <rich-text nodes="{{item.content}}"></rich-text>
</view>

js

http.postReq('article/detailTest...', {id: that.data.id}, function (res) {
    //處理富文本圖片
    let list = res.data;
    for (var i = 0, len = list.length; i < len; i++) {
        if (list[i].content != 0) {
            list[i].content = list[i].content.replace(/\<img/gi, '<img style="width:100%;height:auto" ')
            this.setData({
                helpInfoData: list[i]
            })
        }
    }
}

後臺返回數據效果圖

在這裏插入圖片描述

微信小程序模板消息

注意: 需要用戶先在小程序內通過交互行爲觸發事件report-submit 設置爲 true

表單提交:獲取 formId

支付: 獲取 prepay_id

官方API

詳情請見之前總結節點

wxml

<!-- 使用表單 交互行爲後觸發 -->
<form bindsubmit="submitInfo" report-submit='true' >
    <button form-type="submit">立即開始</button>
</form>

js

//獲取formId
submitInfo: function (e) {
    console.log("formId", e.detail.formId);
}

微信小程序textarea穿透問題

項目中遇到需求是場景一,思路都一樣,看個人應用場景

常見應用場景

  • 點擊某按鈕提交textarea數據
  • textarea失去焦點觸發bindblur事件

效果圖

請忽略圖片,我在不同設備中截的圖

在這裏插入圖片描述

處理方式

a. 定義變量showModal控制顯示或隱藏, b. 定義標籤操作(這裏用text)

textarea輸入的內容, 獲取保存, 當點擊按鈕提交數據時把渲染text標籤 , 隱藏textarea

wxml

<view class="textarea">
    <textarea
        placeholder="請您詳細描述故障的情況,我們會盡快處理!"
        placeholder-class="inputColor"
        maxlength="150"
        bindinput="bindTextArea"
        wx:if="{{!showModal}}"
    />
    <!-- 點擊提交時顯示 -->
    <text class='tmpArea' wx:else>{{areaVal}}</text>
</view>

js

// 1. 在 data 初始數據
data: {
    showModal: false
}

// 2. 在 bindTextArea事件上獲取值
bindTextArea: function(e) {
    this.setData({
        areaVal: e.detail.value
    })
}	

// 3. 點擊按鈕提交 改變showModal狀態
this.setData({
    showModal: true
})

textarea監聽輸入內容length

效果圖

在這裏插入圖片描述

wxml

<view class="textarea">
    <textarea
       placeholder="請您詳細描述故障的情況,我們會盡快處理!"
       placeholder-class="inputColor"
       maxlength="150"
       bindinput="bindTextArea"
       wx:if="{{!showModal}}"
    />
    <text class='tmpArea' wx:else>{{areaVal}}</text>
</view>
<!-- 當前length -->
<view class="monitorTxtNum">{{currentWordNumber}}/150</view>

js

// 1. 在 data 初始數據
data: {
    currentWordNumber: 0,
}
    
// 2. 監聽事件獲取值
bindTextArea: function(e) {
    var areaVal = e.detail.value;
    // 獲取輸入框內容的長度
    var len = areaVal.length;
    this.setData({
       currentWordNumber: len //當前字數
    });
}

微信小程序媒體查詢

例舉幾個, 其它設備也一樣格式, iPhone x等適配, 可參考這篇文章

/* iPhone4 */
        @media screen and (device-width: 320px) and (device-height: 480px) and (-webkit-device-pixel-ratio: 2){
}

/* iPhone5 */
@media screen and (device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2){
    
}

/* iPhone X, iPhone XS */
@media only screen and (device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) {
    .testBox {
        font-size: 68rpx;
    }
}

/* iPhone XR */ 
@media only screen and (device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio: 2) {
    .testBox {
       font-size: 78rpx;
    }
}

/* iPhone XS Max */
@media only screen and (device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio: 3) {
    .testBox {
       font-size: 78rpx;
    }
}

scroll-view

使用scroll-view可滾動到對應區域,
注意: 使用豎向滾動時,需要給scroll-view一個固定高度,通過 WXSS 設置 height。

完整請點擊此文章

效果圖

下圖: 標題採用scroll-x橫向滾動,內容採用scroll-y縱向滾動,當點

在這裏插入圖片描述

wxml

<!-- 使用scroll-view 滾動到對應位置 -->
<view class="scrollViewWrap">
    <!-- 分類 -->
    <view  class="cagetory-scroll">
        <scroll-view scroll-x="true" scroll-into-view="NAV{{status}}" scroll-with-animation="true">
            <text bindtap="getStatus" id="NAV{{index}}" class="cagetory-nav-li {{index === status ? 'cagetory-nav-active' : ''}}" data-index="{{index}}" wx:for="{{navList}}" wx:key="">{{item}}</text>
        </scroll-view>
    </view>

    <!-- 內容 -->
    <view class="cagetory-fixed-y">
        <scroll-view class="cagetory-scroll-y" scroll-y="true" scroll-into-view="NAV{{status}}" scroll-with-animation="true">
            <view wx:for="{{navList}}" wx:key="">
                <view id="NAV{{index}}" class="cagetory-list-head">{{item}}</view>
                <view class="cagetory-list-li">{{item}} 分類 {{index}}</view>
            </view>
        </scroll-view>
    </view>
</view>

js

Page({

    /**
     * 頁面的初始數據
     */
    data: {
        toView: '',
        navList: [
            "關注",
            "推薦",
            "時常",
            "正能量",
            "科技",
            "運動",
            "小視頻",
            "生活",
            "體育",
            "軍事",
        ],
    },
    getStatus(e) {
        console.log('獲取值', e);
        this.setData({
            // 獲取當前index
            status: e.currentTarget.dataset.index,
        })
    },
})

微信小程序跳轉h5頁面

通過web-view承載網頁的容器。web-view會默認自動打開所跳轉的頁面,
項目中遇到需求: 點擊觸發時跳轉h5頁面。 這裏方式新建一個頁面來承載網頁。
注意: 個人類型的小程序暫不支持使用

  • 例: 新建一個頁面out
  • 觸發行爲後跳轉out頁面
  • 在out的wxml中寫上web-view並跳轉的h5url

觸發跳轉

toShopping: function() {
    wx.navigateTo({
        url: '/pages/out/out'
    })
}

wxml

<!-- 跳轉h5 src填寫要跳轉url -->
<web-view src="http://newmall.test.com"></web-view>

<!-- 帶參數 -->
<web-view src="{{url}}/mobile/#/billingRule?lng={{lng}}&lat={{lat}}"></web-view>

h5頁面返回微信小程序

h5返回小程序 組件使用

第一步: h5頁面引入js

<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>

第二步:判斷當前環境

方式一:

參考1:

    /**
    * 方式 1: 
    * 封裝爲公共方法
    */
    //檢測是否是微信小程序環境
    export const isMiniProgram = () =>{
        var ua = navigator.userAgent.toLowerCase();
        var envType='#';
    
        if(ua.match(/MicroMessenger/i) == 'micromessenger'){ //微信環境
            wx.miniProgram.getEnv(function(res) {
                if (res.miniprogram) { // 小程序環境下邏輯
                    envType = true
                }else { //非小程序環境下邏輯
                    envType =  false
                }
            })
        }else{ //非微信環境邏輯
            envType = false
        }
        return envType
    }

方式二:

在網頁內可通過window.__wxjs_environment變量判斷是否在小程序環境,建議在WeixinJSBridgeReady回調中使用,也可以使用JSSDK 1.3.2提供的getEnv接口。

    // web-view下的頁面內
    function ready() {
      console.log(window.__wxjs_environment === 'miniprogram') // true
    }
    
    if (!window.WeixinJSBridge || !WeixinJSBridge.invoke) {
      document.addEventListener('WeixinJSBridgeReady', ready, false)
    } else {
      ready()
    }
    
    // 或者 (同方式一)
    wx.miniProgram.getEnv(function(res) {
      console.log(res.miniprogram) // true
    }

第三步:使用

這裏是在vue頁面內使用

    //引入
    import { isMiniProgram } from '@/api/commonApi'
    
    //需要地方調用
    let isMini = isMiniProgram();
    if(isMini == true){  //小程序環境
        Toast.clear();//清掉
        //返回 小程序
        wx.miniProgram.navigateTo({url: '/pages/h5pay/h5pay?id='+this.id+'&action=orderpay&paytype='+this.paytype});
        return ;
    }

微信小程序防止多次點擊

這裏demo: 一分鐘內只能提交一次

    //獲取當前分鐘
    var minute = date.getMinutes().toString();
    if (minute != wx.getStorageSync('minute')) {
        // 存儲本地
        wx.setStorageSync('minute', minute)
        console.log('點擊我了');
    } else {
        wx.showToast({
            title: '提交太頻繁了。',
            icon: 'none'
        })
        return;
    } 

微信小程序使用iconfont圖標

小程序中使用字體圖標,和h5頁面中使用差不多
注意:有些文章說明需把iconfont.ttf文件轉成base64格式,我下載發現字體圖標文件iconfont.css中本身是base64格式。這樣無需轉換格式,直接使用。

下載iconfont

下載圖標步驟效果圖

  • 找到需要的icon
  • 鼠標懸浮icon上添加到購物車
  • 右上角找到購物車圖標,點擊添加到項目中
  • 點擊查看在線鏈接—>點擊生成
  • 點擊下載本地
    在這裏插入圖片描述

使用

  • 找到剛下載的iconfont文件中的iconfont.css文件, copy一份修改後綴爲iconfont.wxss
  • 在需要的使用的.wxss中引入iconfont.wxss文件, 可修改顏色icon大小
    // 引入文件
    @import '/utils/iconfont/iconfont.wxss';
    
    // wxml中使用
    <view class="iconfont icon-jia_"></view>

微信小程序分享好友

使用onShareAppMessage事件監聽用戶點擊頁面內按鈕分享或右上角三個圓點中的轉發按鈕的行爲, 可自定義轉發內容分享好友。通過 ( button組件open-type="share"
轉發描述信息及注意事項

效果圖

注意: 圖片未指定: 默認截取當前頁的80%

在這裏插入圖片描述

wxml

	<button class='shareBtn' open-type="share" hover-class='none'>馬上邀請</button>

js

/**
 * 用戶點擊右上角分享
 * 當前頁面 path ,必須是以 / 開頭的完整路徑
 * 圖片未指定: 默認截取當前頁的80%
 */
onShareAppMessage: function() {
    var that = this;
    return {
        title: that.data.shareData.title, //轉發標題
        // path: that.data.shareData.link,
        path: '/page/otherPackage/pages/invite/share/share?member_id=' + that.data.userinfo.member_id, //轉發路徑
        desc: that.data.shareData.content, //描述
        imageUrl: that.data.shareData.logimg, //用戶分享出去的自定義圖片大小爲5:4,
        success: function(res) {
            // 轉發成功
            wx.showToast({
                title: "分享成功",
                icon: 'success',
                duration: 2000
            })
        },
        fail: function(res) {
            // 分享失敗
            console.log('分享失敗', res);
        },
    }
},

全屏預覽圖片,分享好友

wx.previewImage(Object object)
在新頁面中全屏預覽圖片。預覽的過程中用戶可以進行保存圖片、發送給朋友等操作。

wxml

 <view class="qrCode">
     <image src="{{shareData.qrcode}}" mode="aspectFit" bindtap="previewImage" data-src="{{shareData.qrcode}}"></image>
 </view>

js

/**
* 圖片點擊預覽、長按識別圖中二維碼
*/
previewImage: function (e) {
    let url = e.currentTarget.dataset.src;
    wx.previewImage({
        current: url, // 當前顯示圖片的http鏈接
        urls: [url] // 需要預覽的圖片http鏈接列表
    })
}
  • 注意: 目前只支持識別小程序碼不能識別普通二維碼

微信小程序獲取元素高度

使用

  • 在需要使用頁面jsonload()方法獲取即可。
/**
* 生命週期函數--監聽頁面加載
*/
onLoad: function(options) {
    let that = this;
    const query = wx.createSelectorQuery()
    query.select('#the-id').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec(function (res) {
        res[0].top       // #the-id節點的上邊界座標
        res[1].scrollTop // 顯示區域的豎直滾動位置
        
        let height = res[0].height;
        console.log(height);
        that.setData({
            topHeight: height
        })
    })
},

小程序中引導用戶關注公衆號

注:設置的公衆號需與小程序主體一致。

前提:

  1. 使用組件前,需前往小程序後臺,在“設置”->“關注公衆號”中設置要展示的公衆號。

  2. 如果小程序後臺中沒有關聯公衆號, 需要在公衆號後臺關聯公衆號

說明:

  • 公衆號關注組件。當用戶掃小程序碼打開小程序時,開發者可在小程序內配置公衆號關注組件,方便用戶快捷關注公衆號,可嵌套在原生組件內。

  • 在一個小程序的生命週期內,只有從以下場景進入小程序,才具有展示引導關注公衆號組件的能力:

    • 當小程序從掃小程序碼場景(場景值1047,場景值1124)打開時
    • 當小程序從聊天頂部場景(場景值1089)中的「最近使用」內打開時,若小程序之前未被銷燬,則該組件保持上一次打開小程序時的狀態
    • 當從其他小程序返回小程序(場景值1038)時,若小程序之前未被銷燬,則該組件保持上一次打開小程序時的狀態

使用

  • 直接在需要使用的頁面, 使用組件。一個頁面只能使用一個組件
	<official-account></official-account>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章