亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Get user information
添加分享功能
帶參分享
全局分享
分享按鈕
頁面跳轉(zhuǎn)
自定義組件
定義全局組件
設(shè)置默認(rèn)頂部導(dǎo)航欄樣式
取消頂部默認(rèn)的導(dǎo)航欄
Home WeChat Applet Mini Program Development Summary of common functions for WeChat mini program development

Summary of common functions for WeChat mini program development

Aug 30, 2022 pm 01:56 PM
WeChat applet

This article brings you relevant knowledge about WeChat Mini Program. It mainly introduces the common functions of WeChat Mini Program development. This article introduces it to you in great detail through example code, which is helpful for your learning. Or the work has certain reference value, I hope it will be helpful to everyone.

Summary of common functions for WeChat mini program development

[Related learning recommendations: 小program learning tutorial]

Get user information

Call The wx.getUserProfile method obtains basic user information. It can only be called after a click event occurs on the page (for example, in the callback of bindtap on button). An authorization window will pop up for each request. After the user agrees, userInfo# will be returned.

##The specific parameters are as follows:

AttributeTypeDefault valueRequiredDescriptionlangstringenNoLanguage for displaying user information descstringis declares the purpose of obtaining the user’s personal information, which shall not exceed 30 characterssuccessfunctionNoCallback function for successful interface callfailfunctionNoCallback function that fails to call the interfacecompletefunctionNoThe callback function at the end of the interface call (will be executed if the call is successful or failed)
Sample code

wx.getUserProfile({
    desc: '用于完善用戶基本資料', // 聲明獲取用戶個(gè)人信息后的用途,不超過30個(gè)字符
    success: (res) => {
        console.log(res.userInfo));
    }
})

Get the return value

{
  "nickName": "秋梓", // 微信昵稱
  "gender": 0,
  "language": "zh_CN",
  "city": "",
  "province": "",
  "country": "",
  "avatarUrl": "https://thirdwx.qlogo.cn/mmopen/vi_32/qrSYVbDbBhunywgP5HTx4mhT8HVNzhmlibd8pfYo4guPJ5w/132" // 頭像
}

Get the mobile phone number

Currently, this interface is for non-individual developers. Mini programs that have completed certification are open (excluding overseas entities). It needs to be used with caution. If users report it frequently or are found to be used in unnecessary scenarios, WeChat has the right to permanently revoke the interface permissions of the mini program.

Usage method

You need to set the value of the button component

open-type to getPhoneNumber. After the user clicks and agrees, you can use bindgetphonenumber The event callback obtains the dynamic token code, then passes code to the developer backend, and calls the phonenumber.getPhoneNumber interface provided by the WeChat backend in the developer backend. Spend code in exchange for the user’s mobile phone number. Each code is valid for 5 minutes and can only be consumed once.

Note: The

code returned by getPhoneNumber has different functions from the code returned by wx.login and cannot be Mix it up.

Code example

<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber"></button>
rrree

Return parameter description

##ParametercodeThen exchange the user's mobile phone number through code. Each code can only be used once, and the validity period of the code is 5min
TypeDescriptionMinimum version
StringDynamic token. Users’ mobile phone numbers can be exchanged for dynamic tokens. Usage details phonenumber.getPhoneNumber interface

Call the following interface

Page({
  getPhoneNumber (e) {
    console.log(e.detail.code)
  }
})

Request parameters

Attributes##access_token / cloudbase_access_tokenstring is the interface call credential codestring is the mobile phone number to obtain the voucher The returned JSON data packet
TypeDefault valueRequiredDescription

attribute TypeDescriptionerrcodenumberError codeerrmsgstringError messagephone_infoObjectUser phone number information

返回結(jié)果示例

{
    "errcode":0,
    "errmsg":"ok",
    "phone_info": {
        "phoneNumber":"xxxxxx",
        "purePhoneNumber": "xxxxxx",
        "countryCode": 86,
        "watermark": {
            "timestamp": 1637744274,
            "appid": "xxxx"
        }
    }
}

實(shí)現(xiàn)微信支付

喚起微信支付的核心方法調(diào)用 wx.requestPayment 方法,該方法具體參數(shù)如下

屬性類型默認(rèn)值必填說明
timeStampstring 時(shí)間戳,從 1970 年 1 月 1 日 00:00:00 至今的秒數(shù),即當(dāng)前的時(shí)間
nonceStrstring 隨機(jī)字符串,長(zhǎng)度為32個(gè)字符以下
packagestring 統(tǒng)一下單接口返回的 prepay_id 參數(shù)值,提交格式如:prepay_id=***
signTypestringMD5 僅在 v2 版本接口適用簽名算法,應(yīng)與后臺(tái)下單時(shí)的值一致
HMAC-SHA256 僅在 v2 版本接口適用
RSA 僅在 v3 版本接口適用
paySignstring 簽名,具體見微信支付文檔
successfunction 接口調(diào)用成功的回調(diào)函數(shù)
failfunction 接口調(diào)用失敗的回調(diào)函數(shù)
completefunction 接口調(diào)用結(jié)束的回調(diào)函數(shù)(調(diào)用成功、失敗都會(huì)執(zhí)行)
/**
 * 微信支付方法
 * @param {string} oderId 訂單id
 * @param {string} total 訂單金額
 * @param {stromg} openId 登陸人openid
 */
function weixinPayFun(data) {
  wx.showLoading({
    mask: true
  })
  const http = new Http()
  return new Promise((resolve, reject) => {
    // 請(qǐng)求支付接口
    http.post(`${env.fayongApi}/app/shopping/order/pay`, data).then(res => {
      // 獲取支付簽名信息
      let payInfo = res.data
      // 調(diào)起微信支付
      wx.requestPayment({
        "timeStamp": payInfo.timeStamp + &#39;&#39;,
        "nonceStr": payInfo.nonceStr,
        "package": payInfo.package,
        "signType": "RSA",
        "paySign": payInfo.paySign,
        "success": function (res) {
          console.log(res, &#39;success&#39;);
          // 支付成功
          resolve(res)
        },
        "fail": function (err) {
          // 支付失敗
          reject(err)
        },
        "complete": function (res) {
          wx.hideLoading()
        }
      })
    })
  })
}

添加分享功能

在需要分享的分享的頁面中添加 onShareAppMessage 事件函數(shù),此事件處理函數(shù)需要 return 一個(gè) Object,用于自定義轉(zhuǎn)發(fā)內(nèi)容,只有定義了此事件處理函數(shù),右上角菜單才會(huì)顯示“轉(zhuǎn)發(fā)”按鈕

onShareAppMessage 方法具體參數(shù)如下

字段說明默認(rèn)值最低版本
title轉(zhuǎn)發(fā)標(biāo)題當(dāng)前小程序名稱
path轉(zhuǎn)發(fā)路徑當(dāng)前頁面 path ,必須是以 / 開頭的完整路徑
imageUrl自定義圖片路徑,可以是本地文件路徑、代碼包文件路徑或者網(wǎng)絡(luò)圖片路徑。支持PNG及JPG。顯示圖片長(zhǎng)寬比是 5:4。使用默認(rèn)截圖1.5.0
promise如果該參數(shù)存在,則以 resolve 結(jié)果為準(zhǔn),如果三秒內(nèi)不 resolve,分享會(huì)使用上面?zhèn)魅氲哪J(rèn)參數(shù) 2.12.0

靜態(tài)分享

示例代碼

Page({
    // 分享
    onShareAppMessage() {
        return {
            title: "樂福健康", // 分享標(biāo)題
            path: "pages/newhome/index", // 分享地址路徑
        }
    }
})

添加完成后點(diǎn)擊右上角膠囊按鈕會(huì)分享圖標(biāo)會(huì)亮起

帶參分享

上面的分享是不帶參數(shù)的,我們可以直接在路徑中動(dòng)態(tài)添加參數(shù),分享后用戶點(diǎn)擊時(shí)會(huì)觸發(fā) onLoad 函數(shù)獲取路徑中的參數(shù)值

// 分享
onShareAppMessage() {
    const that = this;
    return {
        title: that.data.goodInfo.goodName, // 動(dòng)態(tài)獲取商品名稱
        path: "pages/component/orderparticulars/orderparticulars?id=" + that.data.productId, // 動(dòng)態(tài)傳遞當(dāng)前商品id
        imageUrl: that.data.background[0] // 獲取商品封面圖
    }
}

動(dòng)態(tài)獲取分享圖片和標(biāo)題后我們每次分享時(shí)會(huì)出現(xiàn)不同內(nèi)容

全局分享

除此之外我們也可以添加全局分享功能

首先要在每個(gè)頁面中添加 onShareAppMessage 函數(shù),函數(shù)體內(nèi)容可以為空,如果函數(shù)體內(nèi)容為空,則會(huì)使用我們?cè)?app.js 中定義的默認(rèn)分享方法,如果該函數(shù)返回了一個(gè) object 則使用我們自定義的分享功能

在需要被分享的頁面添加如下代碼

Page({
    /**
     * 用戶點(diǎn)擊右上角分享
     */
    onShareAppMessage: function () {
		// 函數(shù)體內(nèi)容為空即可
    }
})

接著在 app.js 中添加重寫分享方法

//重寫分享方法
overShare: function () {
    //間接實(shí)現(xiàn)全局設(shè)置分享內(nèi)容
    wx.onAppRoute(function () {
        //獲取加載的頁面
        let pages = getCurrentPages(),
            //獲取當(dāng)前頁面的對(duì)象
            view = pages[pages.length - 1],
            data;
        if (view) {
            data = view.data;
            // 判斷是否需要重寫分享方法
            if (!data.isOverShare) {
                data.isOverShare = true;
                view.onShareAppMessage = function () {
                    //重寫分享配置
                    return {
                        title: &#39;分享標(biāo)題&#39;,
                        path: "/pages/index/index"    //分享頁面地址
                    };
                }
            }
        }
    })
},

然后在 onLaunch 函數(shù)中調(diào)用該方法

onLaunch() {
    this.overShare()
}

分享按鈕

在開發(fā)中我們也會(huì)碰到點(diǎn)擊分享按鈕實(shí)現(xiàn)分享功能,實(shí)現(xiàn)代碼如下

首先在 html 中添加 button 按鈕。其中 open-typ 要等于 share,表示點(diǎn)擊這個(gè)按鈕注定觸發(fā)分享函數(shù)

<!-- 分享按鈕 -->
<van-button type="primary" icon="share" round class="search" open-type="share" size="small">
    分享
</van-button>

之后要確保我們?cè)?js 中添加了 onShareAppMessage 函數(shù)

效果如下:

獲取用戶收貨地址

獲取用戶收貨地址。調(diào)起用戶編輯收貨地址原生界面,并在編輯完成后返回用戶選擇的地址。

wx.chooseAddress({
    success(res) {
        console.log(res.userName)
        console.log(res.postalCode)
        console.log(res.provinceName)
        console.log(res.cityName)
        console.log(res.countyName)
        console.log(res.detailInfo)
        console.log(res.nationalCode)
        console.log(res.telNumber)
    }
})

參數(shù)說明

屬性類型說明
userNamestring收貨人姓名
postalCodestring郵編
provinceNamestring國(guó)標(biāo)收貨地址第一級(jí)地址
cityNamestring國(guó)標(biāo)收貨地址第二級(jí)地址
countyNamestring國(guó)標(biāo)收貨地址第三級(jí)地址
streetNamestring國(guó)標(biāo)收貨地址第四級(jí)地址
detailInfostring詳細(xì)收貨地址信息(包括街道地址)
detailInfoNewstring新選擇器詳細(xì)收貨地址信息
nationalCodestring收貨地址國(guó)家碼
telNumberstring收貨人手機(jī)號(hào)碼
errMsgstring錯(cuò)誤信息

Preview image

Call method: wx.previewImage(Object object)

Preview the image in full screen on the new page. During the preview process, users can save pictures, send them to friends, etc.

AttributeTypeDefault valueRequiredDescriptionMinimum version
urlsArray. is a list of image links that needs to be previewed . Cloud file ID is supported starting from 2.2.3.
showmenubooleantrueNoWhether to display long press menu. Codes that support identification: Mini Program codes. Only Mini Programs support identification codes: WeChat personal codes, WeChat group codes, corporate WeChat personal codes, corporate WeChat group codes, and corporate WeChat interoperable group codes; 2.13.0
currentstringThe first picture of urlsNoThe link of the currently displayed picture
referrerPolicystringno-referrerNoorigin : Send complete referrer; no-referrer: Do not send. The format is fixed to https://servicewechat.com/{appid}/{version}/page-frame.html, where {appid} is the appid of the mini program and {version} is the version number of the mini program. , the version number is 0, which means the development version, trial version and review version, the version number is devtools, which means the developer tools, and the rest are official versions; 2.13.0
successfunction NoCallback function for successful interface call
failfunction NoCallback function for failed interface call
completefunction NoThe callback function at the end of the interface call (will be executed if the call is successful or failed)

示例代碼

wx.previewImage({
  current: &#39;&#39;, // 當(dāng)前顯示圖片的http鏈接
  urls: [] // 需要預(yù)覽的圖片http鏈接列表
})

頁面跳轉(zhuǎn)

跳轉(zhuǎn)普通頁面

wx.navigateTo({
    url: &#39;&#39;,
})

保留當(dāng)前頁面,跳轉(zhuǎn)到應(yīng)用內(nèi)的某個(gè)頁面。但是不能跳到 tabbar 頁面。使用 wx.navigateBack 可以返回到原頁面。小程序中頁面棧最多十層

跳轉(zhuǎn)tabBar 頁面

跳轉(zhuǎn)到 tabBar 頁面,并關(guān)閉其他所有非 tabBar 頁面

wx.switchTab({
  url: &#39;/index&#39;
})

自定義組件

在小程序中的組件和普通頁面的 js 結(jié)構(gòu)有很大差異,結(jié)構(gòu)如下

// pages/TestComponent/test.js
Component({
    /**
     * 組件的屬性列表
     */
    properties: {
        userName:""
    },

     * 組件的初始數(shù)據(jù)
    data: {
     * 組件的方法列表
    methods: {
        // 獲取父組件傳遞過來的參數(shù)
        getPropName(){
            console.log(this.data.userName);
        }
    }
})

其中我們?cè)?properties 對(duì)象中定義組件組件的屬性列表

然后再組件中添加觸發(fā) getPropName 的方法

<button bind:tap="getPropName">獲取名稱</button>

在我們需要引入這個(gè)組件的頁面去聲明這個(gè)組件的名稱和地址,找到后綴為 json 的文件,添加如下代碼

{
  "usingComponents": {
    "test-component":"../TestComponent/test"
  }
}

之后我們?cè)陧撁嬷邢袷褂闷胀?biāo)簽一樣使用這個(gè)組件,并且給組件傳遞數(shù)據(jù)

<test-component userName="張三"></test-component>

傳遞數(shù)據(jù)后我們即可實(shí)現(xiàn)點(diǎn)擊組件中的按鈕獲取父組件傳遞過來的值

定義全局組件

我們定義完組件后想要在全局使用,我們可以將這個(gè)組件定義為全局組件

首先找到項(xiàng)目中的 app.json 文件,找到 usingComponents 添加組件地址

{
    ......省略其他代碼
    "usingComponents": {
        "test-component":"./pages/TestComponent/test"
    }
}

聲明完成后我們即可在全局像使用標(biāo)簽的方式使用該組件

設(shè)置默認(rèn)頂部導(dǎo)航欄樣式

app.json 中添加如下代碼

{
    "window": {
        "backgroundTextStyle": "light",
        "navigationBarBackgroundColor": "#22a381",
        "navigationBarTitleText": "樂福健康",
        "navigationBarTextStyle": "white"
    }
}

全部參數(shù)列表

屬性類型默認(rèn)值描述最低版本
navigationBarBackgroundColorHexColor#000000導(dǎo)航欄背景顏色,如 #000000
navigationBarTextStylestringwhite導(dǎo)航欄標(biāo)題顏色,僅支持 black / white
navigationBarTitleTextstring 導(dǎo)航欄標(biāo)題文字內(nèi)容
navigationStylestringdefault導(dǎo)航欄樣式,僅支持以下值: default 默認(rèn)樣式 custom 自定義導(dǎo)航欄,只保留右上角膠囊按鈕。iOS/Android 微信客戶端 7.0.0,Windows 微信客戶端不支持
backgroundColorHexColor#ffffff窗口的背景色
backgroundTextStylestringdark下拉 loading 的樣式,僅支持 dark / light
backgroundColorTopstring#ffffff頂部窗口的背景色,僅 iOS 支持微信客戶端 6.5.16
backgroundColorBottomstring#ffffff底部窗口的背景色,僅 iOS 支持微信客戶端 6.5.16
enablePullDownRefreshbooleanfalse是否開啟當(dāng)前頁面下拉刷新。 詳見 Page.onPullDownRefresh
onReachBottomDistancenumber50頁面上拉觸底事件觸發(fā)時(shí)距頁面底部距離,單位為px。 詳見 Page.onReachBottom
pageOrientationstringportrait屏幕旋轉(zhuǎn)設(shè)置,支持 auto / portrait / landscape 詳見 響應(yīng)顯示區(qū)域變化2.4.0 (auto) / 2.5.0(landscape)
disableScrollbooleanfalse設(shè)置為 true 則頁面整體不能上下滾動(dòng)。 只在頁面配置中有效,無法在 app.json 中設(shè)置
usingComponentsObject頁面自定義組件配置1.6.3
initialRenderingCachestring 頁面初始渲染緩存配置,支持 static / dynamic2.11.1
stylestringdefault啟用新版的組件樣式2.10.2
singlePageObject單頁模式相關(guān)配置2.12.0
restartStrategystringhomePage重新啟動(dòng)策略配置2.8.0

效果

取消頂部默認(rèn)的導(dǎo)航欄

找到頁面 json 文件添加 "navigationStyle":"custom",即可去掉默認(rèn)導(dǎo)航欄

{
  "usingComponents": {
      
  },
  "navigationStyle":"custom"
}

添加自定義樣式后可以達(dá)到如下效果

【相關(guān)學(xué)習(xí)推薦:小程序?qū)W習(xí)教程

The above is the detailed content of Summary of common functions for WeChat mini program development. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Xianyu WeChat mini program officially launched Xianyu WeChat mini program officially launched Feb 10, 2024 pm 10:39 PM

Xianyu's official WeChat mini program has quietly been launched. In the mini program, you can post private messages to communicate with buyers/sellers, view personal information and orders, search for items, etc. If you are curious about what the Xianyu WeChat mini program is called, take a look now. What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3. If you want to use it, you must activate WeChat payment before you can purchase it;

Implement image filter effects in WeChat mini programs Implement image filter effects in WeChat mini programs Nov 21, 2023 pm 06:22 PM

Implementing picture filter effects in WeChat mini programs With the popularity of social media applications, people are increasingly fond of applying filter effects to photos to enhance the artistic effect and attractiveness of the photos. Picture filter effects can also be implemented in WeChat mini programs, providing users with more interesting and creative photo editing functions. This article will introduce how to implement image filter effects in WeChat mini programs and provide specific code examples. First, we need to use the canvas component in the WeChat applet to load and edit images. The canvas component can be used on the page

Implement the drop-down menu effect in WeChat applet Implement the drop-down menu effect in WeChat applet Nov 21, 2023 pm 03:03 PM

To implement the drop-down menu effect in WeChat Mini Programs, specific code examples are required. With the popularity of mobile Internet, WeChat Mini Programs have become an important part of Internet development, and more and more people have begun to pay attention to and use WeChat Mini Programs. The development of WeChat mini programs is simpler and faster than traditional APP development, but it also requires mastering certain development skills. In the development of WeChat mini programs, drop-down menus are a common UI component, achieving a better user experience. This article will introduce in detail how to implement the drop-down menu effect in the WeChat applet and provide practical

What is the name of Xianyu WeChat applet? What is the name of Xianyu WeChat applet? Feb 27, 2024 pm 01:11 PM

The official WeChat mini program of Xianyu has been quietly launched. It provides users with a convenient platform that allows you to easily publish and trade idle items. In the mini program, you can communicate with buyers or sellers via private messages, view personal information and orders, and search for the items you want. So what exactly is Xianyu called in the WeChat mini program? This tutorial guide will introduce it to you in detail. Users who want to know, please follow this article and continue reading! What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3.

WeChat applet implements image upload function WeChat applet implements image upload function Nov 21, 2023 am 09:08 AM

WeChat applet implements picture upload function With the development of mobile Internet, WeChat applet has become an indispensable part of people's lives. WeChat mini programs not only provide a wealth of application scenarios, but also support developer-defined functions, including image upload functions. This article will introduce how to implement the image upload function in the WeChat applet and provide specific code examples. 1. Preparatory work Before starting to write code, we need to download and install the WeChat developer tools and register as a WeChat developer. At the same time, you also need to understand WeChat

Use WeChat applet to achieve carousel switching effect Use WeChat applet to achieve carousel switching effect Nov 21, 2023 pm 05:59 PM

Use the WeChat applet to achieve the carousel switching effect. The WeChat applet is a lightweight application that is simple and efficient to develop and use. In WeChat mini programs, it is a common requirement to achieve carousel switching effects. This article will introduce how to use the WeChat applet to achieve the carousel switching effect, and give specific code examples. First, add a carousel component to the page file of the WeChat applet. For example, you can use the &lt;swiper&gt; tag to achieve the switching effect of the carousel. In this component, you can pass b

Implement image rotation effect in WeChat applet Implement image rotation effect in WeChat applet Nov 21, 2023 am 08:26 AM

To implement the picture rotation effect in WeChat Mini Program, specific code examples are required. WeChat Mini Program is a lightweight application that provides users with rich functions and a good user experience. In mini programs, developers can use various components and APIs to achieve various effects. Among them, the picture rotation effect is a common animation effect that can add interest and visual effects to the mini program. To achieve image rotation effects in WeChat mini programs, you need to use the animation API provided by the mini program. The following is a specific code example that shows how to

Implement the sliding delete function in WeChat mini program Implement the sliding delete function in WeChat mini program Nov 21, 2023 pm 06:22 PM

Implementing the sliding delete function in WeChat mini programs requires specific code examples. With the popularity of WeChat mini programs, developers often encounter problems in implementing some common functions during the development process. Among them, the sliding delete function is a common and commonly used functional requirement. This article will introduce in detail how to implement the sliding delete function in the WeChat applet and give specific code examples. 1. Requirements analysis In the WeChat mini program, the implementation of the sliding deletion function involves the following points: List display: To display a list that can be slid and deleted, each list item needs to include

See all articles