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

Table of Contents
1. Potential pitfalls and Tips that may be encountered during development
-s
2.2 自己實(shí)現(xiàn)
2.3 在項目中使用
3. setState 修改 data 中想修改對象的屬性
3.1 為什么要使用 wx-updata
3.2 wx-updata 使用方式
4. 使用 scss 寫樣式
4.1 Webstorm 配置方法
4.2 Visual Studio Code 配置方法
5. 使用 iconfont 圖標(biāo)字體
Home WeChat Applet Mini Program Development Several simple and practical WeChat mini program development tips that are highly recommended

Several simple and practical WeChat mini program development tips that are highly recommended

Oct 10, 2020 pm 05:34 PM
WeChat applet development

WeChat Mini Program Development column strongly recommends several simple and practical WeChat Mini Program development tips today.

Several simple and practical WeChat mini program development tips that are highly recommended

I developed a WeChat applet some time ago. During the development process, I summarized some tips that I think are useful to me. I extracted them and it is equivalent to a summary review. I also hope it can help everyone. If it is really helpful to everyone, don’t forget to like it

  1. WeChat Developer Tools Version: 1.03.2006090 (2020-06-19)
  2. Basic library version: v2.12.1 (2020-08-04)

1. Potential pitfalls and Tips that may be encountered during development

I originally wanted to write one As a little trick, I ended up summing up a lot of pitfalls. Before I got started, I had no idea that the development experience of WeChat mini programs was so bad. From WeChat developer tools to the so-called "new language", there is a The strong visual sense of half-finished five really makes me emmm... In addition, I found that most of the small program articles on the Internet are practical articles on how to use and how to avoid pitfalls, rather than technical articles, which also reflects from the side. There are many pitfalls in mini programs.

During the native development process of WeChat mini-programs, I kept asking questions like "Why would Tencent, which has so many talented technical people, launch such a stupid thing?" Many mentally retarded and anti-human things were discovered in the community two or three years ago. It has been raised, and the official reply has reported that it is being repaired, but several years have passed and there is still no news. The official reply is still a cold "Feedback"

  1. WeChat developer tools are often not hotly updated. Even if it works, the screen will be white. Even recompiling won't work. I can only force quit and open it again;
  2. is similar to the previous one. Sometimes there is a mistake in the style, and the entire preview will be white, and the debugger will not tell where it is. The problem will be abandoned and not displayed. Recompiling cannot solve the problem. You can only force quit and open it again;
  3. is similar to the previous one. The errors reported in the debugger are often useless and the donkey's head is wrong. The horse's mouth makes it difficult to locate the problem;
  4. The custom Tabbar on Android will also move down with the screen when it is pulled down to refresh, and it is a bug that cannot be bypassed. The custom Tabbar style is written Okay, I changed it to the built-in Tabbar again! The path of
  5. import does not support absolute paths. For example, if you want to reference utils/fetch.js, you must slowly ## no matter how deep the component is. #../ Click to the root directory, and similarly .wxss file @import can only use relative paths when importing files, so ../ will appear ../../../../../utils/fetch.js This kind of thing;
  6. The static resource path cannot have Chinese characters, and if there are Chinese characters, it cannot be loaded;
  7. # The
  8. ##.wxs
  9. file does not support ES6 and can only use the crappy ES5 writing method; only the .wxs file can be imported into
  10. .wxml Can't import .js file? ? ? Template
  11. {{}}
  12. Even the methods cannot be executed and can only handle simple operations such as - * /. If you encounter data, you need filter scenarios need to be pre-formatted in the .js file and setData one by one, such as [2,3,4].includes( type), can’t even run! The Date object cannot be used in the
  13. .wxs file, so you cannot new Date() and can only use the crappy getDate method, the same is true for regular expressions. To generate regular expression objects, you need to use the getRegExp function getRegExp(pattern[, flags]);
  14. .wxs
  15. You can call other .wxs files, and you can only require calling .wxs files. The imported files must use relative paths;
  16. setData
  17. I don’t even bother to merge an object. If data: {a: {b: 1, c: 1}}, then setData({a: {b: 2}}) The value of a.c will be lost, which is really annoying. You have to setData({['a.b': 2]}) like this; ##Date
  18. objects on #IOS get any time parameters such as
  19. getDay, getTime are all NaN, because the Date constructor of IOS does not support 2018-04 -26 The date in this format must be converted to 2018/04/26 This format will be displayed normally; Sometimes the request of the development version applet cannot be sent inexplicably , there are three dots in the upper right corner of enable debug. After opening "Development and Debugging", outgoing requests can be sent inexplicably. This is the case on many mobile phones. The truth is unknown.
  20. 2. WeChat requests Promise transformation
2.1 Use the ready-made library

Install the Promise library wx-promise-pro, remember to bring

-s

or

--production, otherwise the build will not be successful.

npm i -S wx-promise-pro復(fù)制代碼
Then in app.js

:

import { promisifyAll } from 'wx-promise-pro'promisifyAll()  // promisify all wx apiApp({ ... })復(fù)制代碼
Then you can use it normally:
wx.pro.showLoading({    title: '加載中',    mask: true})
  .then(() => console.log('in promise ~'))復(fù)制代碼

2.2 自己實(shí)現(xiàn)

其實(shí)我們可以自己來實(shí)現(xiàn)一個這樣的庫,原理很簡單,以原生 API 的 wx.request 為例:

// 原生 API 使用方式wx.request({    url: '',     // 請求的 url
    data: {},    // 參數(shù)
    method: '',  // post、get
    success: res => {        // 請求成功回調(diào)函數(shù),res為回調(diào)參數(shù)
    },    fail: res => {        // 請求失敗回調(diào)函數(shù),res為回調(diào)參數(shù)
    }
})復(fù)制代碼

如果我們將其 Promise 化,應(yīng)該的調(diào)用方式希望是:

// Promise 化后的期望使用方式wx.pro.request({    url: '',     // 請求的 url
    data: {},    // 參數(shù)
    method: ''   // post、get})
  .then(res => {      // 請求成功回調(diào)函數(shù),res為回調(diào)參數(shù)
  })
  .catch(res => {      // 請求失敗回調(diào)函數(shù),res為回調(diào)參數(shù)
  })復(fù)制代碼

并且 then 函數(shù)返回的是一個 Promise 對象,讓這個函數(shù)可以不斷鏈?zhǔn)秸{(diào)用下去,所以首先需要 new 出來一個 Promise 對象:

function request(opt) {    return new Promise((resolve, reject) => {
        wx.request({
            ...opt,            success: res => { resolve(res)},            fail: res => {reject(res)}
        })
    })
}復(fù)制代碼

這里代碼我們可以進(jìn)一步改進(jìn),由于 success、fail 這里傳入的參數(shù)只是由 resolve、reject 方法執(zhí)行了下,所以可以直接傳入 resolve、reject 方法即可。

另外,由于其他小程序原生 API 格式一致,所以我們可以使用柯里化方法,來將其他需要進(jìn)行 Promise 化的 API 進(jìn)行處理:

function promisify(api) {    return (opt = {}) => {        return new Promise((resolve, reject) => {
            api({
                ...opt,                fail: reject,                success: resolve
            })
        })
    }
}復(fù)制代碼

然后,將柯里化方法執(zhí)行的結(jié)果作為新的 Promise 化的 API 掛載到 wx.pro 對象上:

// 將指定 API 進(jìn)行 Promise 化wx.pro.request = promisify(wx.request)// 使用wx.pro.request({...})
    .then(...)復(fù)制代碼

然后為了方便我們使用其他方法,可以循環(huán)將 wx 對象上可以被 Promise 化的方法比如 request、scanCode、showToast、getUserInfo 等一一掛載到 wx.pro 對象上,使用時可以直接 wx.pro.xx,由于這個方法執(zhí)行返回的是一個 Promise 對象,因此可以像其它 Promise 化的對象那樣使用。

事實(shí)上,不知不覺,我們就自己實(shí)現(xiàn)了 wx-promise-pro 的源碼,這個庫的核心代碼也就是上面那這幾行

2.3 在項目中使用

有了上面的工具后,我們可以將其使用在項目中,為了不在項目中遍布 wx.requestwx.pro.request 這里可以簡單進(jìn)行封裝,新建兩個文件如下:

// utils/api/fetch.js 封裝請求方法、請求攔截器const app = getApp()const BaseUrl = 'http://172.0.0.1:7300/mock'const TokenWhiteList = [    '/app/user/get-by-code'     // 不需要鑒權(quán)的api手動添加到這里]/**
 * 設(shè)置請求攔截器
 * @param params 請求參數(shù)
 */const fetch = (params = {}) => {    // 攔截器邏輯
    if (!TokenWhiteList.includes(params.url)) {
        params.header = {            'content-type': 'application/json',             // 默認(rèn)值
            'token': app.globalData.token || ''
        }
    }    if (params.url.startsWith('/')) {    // 拼接完整URL
        params.url = BaseUrl + params.url
    }    // 返回promise
    return wx.pro.request({ ...params })
      .then(({ data: { code, message, data } }) => {          // ... 各種異常情況的邏輯處理
          // 與后端約定 code 20000 時正常返回
          if (code === 20000) return Promise.resolve(data)          return Promise.reject(message)
      })
}export { fetch }復(fù)制代碼

然后再將所有 API 封裝到單獨(dú)的文件中集中管理:

// utils/api/apis.js 封裝所有請求 APIimport { fetch } from './fetch'/* 根據(jù)微信code獲取用戶信息 */const appUserGetByCode = ({ code } = {}) => fetch({    url: '/app/user/get-by-code',    data: { code }
})/* 掃碼登錄 */const appUserQrLogin = ({ qrCode } = {}) => fetch({    method: 'POST',    url: '/app/user/qr-login',    data: { qrCode }
})/* 個人信息 */const appUserInfo = () => fetch({    url: '/app/user/info'})/* 系統(tǒng)參數(shù)獲取,數(shù)據(jù)字典 */const appSysParamListByParam = () => fetch({    url: '/app/sys-param/list-by-param'})/* 數(shù)據(jù)字典所有 */const appSysParamListAll = () => fetch({    url: '/app/sys-param/list-all'})export {
    appSysParamListAll,   // 數(shù)據(jù)字典所有
    appSysParamListByParam,   // 系統(tǒng)參數(shù)獲取,數(shù)據(jù)字典
    appUserGetByCode,   // 根據(jù)微信code獲取用戶信息
    appUserQrLogin,   // 掃碼登錄
    appUserInfo   // 個人信息}復(fù)制代碼

在要使用 API 的地方就可以這樣引入:

import * as Api from '../../utils/api/apis.js'   // 相對路徑// 使用方式Api.appSysParamListAll()
  .then(({ dataList }) => this.upData({ sysParamList: dataList }))
  .then(() => {      const keyList = this.data.sysParamList.map(T => T.key)      this.upData({
          keyList,          formData: { keys: keyList }
      })
  })復(fù)制代碼

使用方式就很舒服,這里使用到了 upData,就是下面我要介紹的內(nèi)容,是在下非常推介的小程序工具~

3. setState 修改 data 中想修改對象的屬性

在小程序中,data 是不能直接操作的,需要使用 setData 函數(shù)。鑒于微信小程序開發(fā)時 setData 的使用體驗(yàn)十分蹩腳,我使用了個庫函數(shù) wx-updata,這個庫函數(shù)在開發(fā)的時候?qū)ξ液苡袔椭?,這里特意推介給大家。

3.1 為什么要使用 wx-updata

你在使用 setData 的時候,是不是有時候覺得很難受,舉個簡單的例子:

// 你的 datadata: {    name: '蠟筆小新',    info: { height: 140, color: '黃色' }
}復(fù)制代碼

如果要修改 info.height 為 155,使用 setData 要怎么做呢:

// 這樣會把 info 里其他屬性整不見了this.setData({ info: { height: 155 } })// 你需要取出 info 對象,修改后整個 setDataconst { info } = this.data
info.height = 155this.setData({ info })復(fù)制代碼

似乎并不太復(fù)雜,但如果 data 是個很大的對象,要把比較深且不同的對象、數(shù)組項挨個改變:

data: {    name: '蠟筆小新',    info: {        height: 140, color: '黃色',        desc: [{ age: 8 }, '最喜歡大象之歌', '靚仔', { dog: '小白', color: '白色' }]
    }
}復(fù)制代碼

比如某個需求,需要把 info.height 改為 155,同時改變 info.desc 數(shù)組的第 0 項的 age 為 12,第 3 項的 color 為灰色呢?

// 先取出要改變的對象,改變數(shù)字后 setData 回去const { info } = this.data
info.height = 155info.desc[0].age = 12info.desc[3].color = '灰色'this.setData({ info })// 或者像某些文章里介紹的,這樣可讀性差,也不太實(shí)用this.setData({    'info.height': 155,    'info.desc[0].age': 12,    'info.desc[3].color': '灰色'})復(fù)制代碼

上面這兩種方法,是我們平常小程序里經(jīng)常用的,和其他 Web 端的框架相比,就很蹩腳,一種濃濃的半成品感撲面而來,有沒有這樣一個方法:

this.upData({    info: {        height: 155,        desc: [{ age: 12 }, , , { color: '灰色' }]
    }
})復(fù)制代碼

這個方法會幫我們深度改變嵌套對象里對應(yīng)的屬性值,跳過數(shù)組項里不想改變的,只設(shè)置我們提供了的屬性值、數(shù)組項,豈不是省略了一大堆蹩腳的代碼,而且可讀性也極佳呢。

這就是為什么我在上線的項目中使用 wx-updata,而不是 setData

wx-updata 的原理其實(shí)很簡單,舉個例子:

this.upData({    info: {        height: 155,        desc: [{ age: 12 }]
    }
})// 會被自動轉(zhuǎn)化為下面這種格式,// this.setData({//    'info.height': 155,//    'info.desc[0].age': 12,// })復(fù)制代碼

原來這個轉(zhuǎn)化工作是要我們自己手動來做,現(xiàn)在 wx-updata 幫我們做了,豈不美哉!

3.2 wx-updata 使用方式

在一般情況下,我們可以將方法直接掛載到 Page 構(gòu)造函數(shù)上,這樣就可以在 Page 實(shí)例中像使用 setData 一樣使用 upData 了:

// app.js 中掛載import { updataInit } from './miniprogram_npm/wx-updata/index'  // 你的庫文件路徑App({
    onLaunch() {
        Page = updataInit(Page, { debug: true })
    }
})// 頁面代碼中使用方式this.upData({    info: { height: 155 },    desc: [{ age: 13 }, '帥哥'],    family: [, , [, , , { color: '灰色' }]]
})復(fù)制代碼

有的框架可能在 Page 對象上進(jìn)行了進(jìn)一步修改,直接替換 Page 的方式可能就不太好了,wx-updata 同樣暴露了工具方法,用戶可以在頁面代碼中直接使用工具方法進(jìn)行處理:

// 頁面代碼中import { objToPath } from './miniprogram_npm/wx-updata/index'  // 你的庫文件路徑Page({    data: { a: { b: 2}, c: [3,4,5]},    // 自己封裝一下
    upData(data) {        return this.setData(objToPath(data))
    },    // 你的方法中或生命周期函數(shù)
    yourMethod() {        this.upData({ a: { b: 7}, c: [8,,9]})
    }
})復(fù)制代碼

針對修改數(shù)組指定項的時候,可能存在的跳過數(shù)組空位的情況,wx-updata 提供了 Empty 的 Symbol 類型替位符,還有數(shù)組的對象路徑方式,感興趣可以看看 wx-updata 的文檔,也可以參考 <開發(fā)微信小程序,我為什么放棄 setData,使用 upData> 這篇介紹文章。

另外,使用了 wx-updata 也還可以使用原來的 setData,特別是有時候要清空數(shù)組時,靈活使用,可以獲得更好的小程序開發(fā)體驗(yàn),祝大家小程序開發(fā)愉快

4. 使用 scss 寫樣式

4.1 Webstorm 配置方法

關(guān)于蹩腳的 .wxss 樣式,我使用 webstorm 的 file watcher 工具把 scss 文件監(jiān)聽改動并實(shí)時編譯成 .wxss 文件,感覺比較好用,這里給大家分享一下我的配置:

然后記得在 .gitignore 文件中加入要忽略的樣式:

*.scss
*.wxss.map復(fù)制代碼

這樣在上傳到 git 的時候,就不會上傳 scss 文件了~ 當(dāng)然如果你的團(tuán)隊成員需要 scss 的話,還是建議 git 上傳的時候也加上 scss 文件。

這樣設(shè)置之后,一個組件在本地的會是下面這樣

Several simple and practical WeChat mini program development tips that are highly recommended

其中我們需要關(guān)注的就是 .js、.json、.scss、.wxml 文件,另外的文件 .wxss 會在你改動 .scss 文件之后自動生成并更新,而 .wxss.map 是插件自動生成的映射關(guān)系,不用管。

如果不是使用 webstorm,可以直接執(zhí)行命令 sass --watch index.scss:index.wxss -s expanded,命令行如果關(guān)閉,sass 命令就不會監(jiān)聽文件的變動然后編譯,所以最好用編輯器的插件。

同理,也可以使用 less、stylus 等預(yù)編譯語言。

4.2 Visual Studio Code 配置方法

萬能的 VSC 當(dāng)然也可以做到這個功能,搜索并下載插件 easy sass,然后在 setting.json 中修改/增加配置:

"easysass.formats": [
  {    "format": "expanded",    "extension": ".wxss"
  },
  {    "format": "compressed",    "extension": ".min.wxss"
  }
]復(fù)制代碼

上面 expanded 是編譯生成的 .wxss 文件,下面 compressed 是壓縮之后的 .wxss 樣式文件,下面這個用不到可以把下面這個配置去掉,然后在 .gitignore 文件中加入要忽略的中間樣式:

*.scss復(fù)制代碼

當(dāng)然也可以不添加,如果你的同事也是實(shí)用 scss 來開發(fā)小程序的話,其他跟上面一樣,至此你就可以在小程序開發(fā)中快樂使用 scss 了~

5. 使用 iconfont 圖標(biāo)字體

在 Web 開發(fā)中 iconfont 可謂是最常用的靈活圖標(biāo)字體工具了,這里介紹一下如何在微信小程序中引入 iconfont 圖標(biāo)。

首先找到你想使用的圖標(biāo)們,點(diǎn)擊購物車之后下載到本地。

Several simple and practical WeChat mini program development tips that are highly recommended

下載到本地是一個壓縮包,解壓縮之后將 iconfont.css 文件復(fù)制到微信小程序的 styles 文件夾中 (在下的習(xí)慣,也可以放到你想放的地方比如 fonts),將后綴改為 .wxss

Several simple and practical WeChat mini program development tips that are highly recommended

app.wxss 中引入樣式:

@import "styles/iconfont.wxss";復(fù)制代碼

然后在 .wxml 中就可以使用剛剛你添加的圖標(biāo)了,Web 使用 i 標(biāo)簽,小程序中使用 text 標(biāo)簽:

<text class="iconfont icon-my-edit" style="color: blue"></text>復(fù)制代碼

如果后面要加新的圖標(biāo),要下載新的 iconfont.css 的文件到本地重命名并覆蓋,重新走一遍這個流程。

相關(guān)免費(fèi)學(xué)習(xí)推薦:微信小程序開發(fā)

The above is the detailed content of Several simple and practical WeChat mini program development tips that are highly recommended. 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)

Hot Topics

PHP Tutorial
1488
72