微信小程序必备开发技能总结(不断更新)

231 阅读10分钟

一、认识小程序项目结构

pages/                          存放页面文件的目录
├── index/                      代表一个页面的目录
│   ├── index.js                页面的逻辑
│   ├── index.wxml              页面的结构相当于,网页开发的html
│   ├── index.wxss              页面的样式,和网页开发的css 差不多
│   └── index.json              页面的个性化配置 
├── logs/
utils/                          存放工具函数的目录
├── util.js                                     
app.js                          启动整个小程序的入口文件                             
app.json                        小程序的全局配置
app.wxss                        全局样式,会影响整个小程序应用
project.config.json             小程序项目配置文件
project.private.config.json     项目私有的配置文件
sitemap.json                    配置是否允许搜索

重点认识下app.json 和index.json

1. app.json

app.json 中有3个比较重要的的配置:pages,window,tabBar

1.1 pages

pages 配置了小程序的页面路径,是一个数组, 第一个代表首页。

{
  "pages": [
    "pages/index/index",
    "pages/list/list"
  ],
  "window": {
    "navigationBarTextStyle": "black",
    "navigationBarTitleText": "Weixin",
    "navigationBarBackgroundColor": "#ffffff"
  },
  "style": "v2"
}

在这里我们新建了两个页面,一个index, 一个list, 当index 在前面的时候,index 就是首页,如果把"pages/index/index" 和"pages/list/list" 顺序交换,list 排到了前面,list 就会变成首页,也就是我们刚打开小程序时看见的页面。

1.2 window

window 有6个比较常用的配置:

window: {
  "navigationBarBackgroundColor": "#f00",
  "navigationBarTextStyle": "black",
  "navigationBarTitleText": "小程序",
  "backgroundColor": "#1d7dfa",
  "backgroundTextStyle": "light",
  "enablePullDownRefresh": true
},
  • navigationBarBackgroundColor 配置标题栏的背景颜色
  • navigationBarTextStyle 配置标题栏的文字颜色值, 只能是black 和white
  • navigationBarTitleText 配置标题栏的文案
  • backgroundColor 下拉刷新时看到的页面背景颜色
  • backgroundTextStyle 配置下拉刷新时的小圆点颜色值, 只能配置light 和dark
  • enablePullDownRefresh 是否出现下拉刷新效果, 默认不出现

navigationBarBackgroundColor, navigationBarTextStyle, navigationBarTitleText 指的是如下图这部分

image.png

backgroundColor``和backgroundTextStyle 一般和enablePullDownRefresh 一起使用,它指的是这部分

image.png

1.3 tabbar

app.json中还可以配置tabbar,具体配置如下

{
  "pages": [
    "pages/index/index",
    "pages/list/list"
  ],
  "window": {
    "navigationBarBackgroundColor": "#f00",
    "navigationBarTextStyle": "black",
    "navigationBarTitleText": "小程序",
    "backgroundColor": "#1d7dfa",
    "backgroundTextStyle": "light",
    "enablePullDownRefresh": true
  },
  "tabBar": {
        "color": "#000000",
        "selectedColor": "#d81e06",
        "position": "bottom",
        "list": [{
            "pagePath": "pages/index/index",
            "text": "首页",
            "iconPath": "/assets/img/index.png",
            "selectedIconPath": "/assets/img/index-on.png"
        }, {
            "pagePath": "pages/list/list",
            "text": "列表",
            "iconPath": "/assets/img/list.png",
            "selectedIconPath": "/assets/img/list-on.png"
        }]
  },
  "style": "v2"
}

tabar 一级配置常用的有4个:

  • color 配置tab 文案的默认颜色
  • selectedColor 配置选中的颜色
  • position 配置tabar 显示在底部还是顶部,只有两个值, bottom, top,需要注意的是,当设置为top 的时候,tabbar 的图标不会显示。
  • list 配置tabar 的列表
    • pagePath 配置tab 跳转的页面地址
    • text 配置tabbar 显示的文案
    • iconPath 配置tabbar 的默认图标
    • selectedIconPath 配置tabar 的选中图标

选中首页时

image.png

选中列表页面时:

image.png

2. index.json

index.json 常用的配置和app.json 中的window 下的配置基本一样,只是在index.json 中不需要window 这个属性了,直接放在一级。index.json 和app.json 配置了相同的属性,但是值不同时,以index.json的为主。 其他页面同理,页面的配置优先级高于全局app.json 的配置。来看下

index.json

{
    "navigationBarBackgroundColor": "#f00",
    "navigationBarTextStyle": "white",
    "navigationBarTitleText": "首页",
    "backgroundColor": "#1d7dfa",
    "backgroundTextStyle": "light",
    "enablePullDownRefresh": true
}

这里我们将navigationBarTitleText 的值改成了首页,navigationBarTextStyle 的值改成了white, 所以现在我们在首页应该看到标题栏的文案是首页,标题栏的文案颜色是白色, 覆盖了app.json的设置

image.png

二、认识小程序常用组件

1. view

view 是一个容器组件,是小程序开发中用得最多得组件,相当于我们平时网页开发中的div 来看一下view 的简单使用:

index.wxml

<view class="box">
    <view class="hello">hello</view>
    <view class="world">world</view>
</view>

index.wxss


.box view {
    width: 200rpx;
    height: 200rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
}
.box .hello {
    background: #610d0d;
}
.box .world {
    background: #333;
}

运行效果:

image.png

2. scroll-view

2.1 sclroll-x和scroll-y

可以配置滚动的属性的组件, 虽然view 也可以实现滚动效果,但是不推荐,需要滚动的时候都使用scroll-view, 因为它不但提供了配置滚动方向的属性,还提供了很多事件监听方法,使用起来非常方便。 先来看下scroll-view的基础使用

index.wxml

<scroll-view scroll-y="{{true}}" class="scroll-wrap">
    <view class="list">
        <view class="item" wx:for="{{list}}" wx:key="{{item.id}}">{{ item.title}}</view>
    </view>
</scroll-view>

index.wxss

.scroll-wrap {
    height: 500rpx;
}
.list .item {
    height: 100rpx;
    font-size: 40rpxrpx;
    line-height: 100rpx;
    border-bottom: 1rpx solid #ded;
}

运行效果

scroll-view-jichu.gif

需要注意两个点:

  • scroll-view 默认是不出现滚动条的,配置属性scroll-x 或者scroll-y才能实现滚动
  • 只是配置了scroll-x 或者scroll-y 还不行,需要加上宽度或者高度

2.2 scroll-left 和scroll-top

scroll-view 还提供了scroll-top 和scroll-left 用于用于设置滚动条初始化的位置,没有设置时默认在最左端和最顶端。 来看下使用,这里以scroll-top 为例:

<scroll-view scroll-y="{{true}}" scroll-top="100rpx"  class="scroll-wrap">
    <view class="list">
        <view class="item" wx:for="{{list}}" wx:key="item.id">{{ item.title}}</view>
    </view>
</scroll-view>

这里我们将scroll-top 设置才能了100rpx 所有滚动条初始化会默认滚动到距例100rpx的位置。

image.png

scroll-left 和scroll-y的设置可以带单位也可以不带单位, 不带单位默认以px 为单位。

2.3 bindscrolltoupper 和 bindscrolltolower

  • bindscrolltoupper 配置用于指定监听滚动条滚动到最左边或者滚动到最上边时触发的回调函数
  • bindscrolltolower 配置用于指定监听滚动条滚动到最右边或者最下边时触发的回调函数

来看下用法,以纵向为例:

index.wxml

<scroll-view 
    scroll-y="{{true}}"
    scroll-top="100rpx"
    class="scroll-wrap"
    bindscrolltoupper="scrlllTopFn"
    bindscrolltolower="scrollBottomFn"
    >
    <view class="list">
        <view class="item" wx:for="{{list}}" wx:key="id">{{ item.title}}</view>
    </view>
</scroll-view>

index.js

// index.js

Page({
  data: {
    list: [
        {
            id: 1,
            title: 'scrill-view 测试--1'
        },
        {
            id: 2,
            title: 'scrill-view 测试 --2'
        },
        {
            id: 3,
            title: 'scrill-view 测试--3'
        },
        {
            id: 4,
            title: 'scrill-view 测试--4'
        },
        {
            id: 5,
            title: 'scrill-view 测试--5'
        },
        {
            id: 6,
            title: 'scrill-view 测试--6'
        },
        {
            id: 7,
            title: 'scrill-view 测试--7'
        },
        {
            id: 8,
            title: 'scrill-view 测试--8'
        },
        {
            id: 9,
            title: 'scrill-view 测试--9'
        },
        {
            id: 10,
            title: 'scrill-view 测试--10'
        },
        {
            id: 11,
            title: 'scrill-view 测试--11'
        },
        {
            id: 12,
            title: 'scrill-view 测试--12'
        }
    ]
  },
  scrlllTopFn () {
      console.log('滚动到顶部了')
  },
  scrollBottomFn () {
      console.log('滚动到底部了')
  }
})

有了这两个回调配置就非常方便了,可以在滚动到底部的时候进行数据的加载,滚动到顶部的时候进行数据的刷新。

这里主要介绍常用功能,更多配置和使用方法可查看官方文档developers.weixin.qq.com/miniprogram…

3. text

text 渲染内联的文本内容,需要注意的一个点是,text 标签内只能嵌套text标签,不能在嵌套其他标签

4. rich-text

rich-text 用来渲染一段带html 标签的内容

用法: index.wxml

<view>
    <rich-text nodes="{{nodeStr}}">
        
    </rich-text>
</view>

index.js

// index.js

Page({
  data: {
    nodeStr: `
        <h1>大标题h1</h1>
        <ul>
            <li>列表</li>
            <li>列表</li>
            <li>列表</li>
            <li>列表</li>
        </ul>
    `
  }
})

运行效果:

image.png

可以看到h1标签和ul li标签都拥有了普通html 的行为。这在需要渲染一段html 内容时会非常有用,比如说想要写文章,用来渲染文章内容。

nodes 的还支持数组的写法:

// index.js

Page({
    data: {
        nodeStr: [{
            name: 'div',
            attrs: {
            class: 'color-red',
            style: 'line-height: 60px; color: red;'
            },
            children: [{
                type: 'node',
                name: 'h1',
                children: [
                    {
                        type: 'text',
                        text: '这是大标题'
                    }
                ]
            },
            {
                name: 'ul',
                children: [
                    {
                        name: 'li',
                        type: 'node',
                        children: [
                            {
                                type: 'text',
                                text: '列表'
                            }
                        ]
                    },
                    {
                        name: 'li',
                        type: 'node',
                        children: [
                            {
                                type: 'text',
                                text: '列表'
                            }
                        ]
                    },
                ]
            }]
        }]

    }
})

运行效果:

image.png

5. image

image 用来渲染图片的,和html 里面的img 一样使用src 属性来加载图片地址。小程序中的图片会有一个默认的宽度和高度,宽度是320px, 高度是240px。 image 除了src 属性外,还有一个重要的属性配置:mode mode 常用的有5个值:scaleToFillaspectFitaspectFillwidthFixheightFix, 默认值是scaleToFill

它们代表的含义如下:

image.png

分别来看下效果, 为了看效果, 我们给图片image 加个边框

index.wxml

<view>
    <image class="img" src="https://img-qn-1.51miz.com/preview/element/00/01/40/33/E-1403387-C0E99A1F.jpg!/quality/90/unsharp/true/compress/true/format/jpg/fh/260"></image>
</view>

index.wxss

.img {
    border: 5rpx solid #f00;
}

运行效果:

image.png 可以看到图片被拉变形,填满了整个image 标签,这是没有写mode 属性的时候的表现 现在我们添加 mode="scaleToFill" 属性,

image.png

可以看到显示没有任何变化,因为之前说过了scaleToFill是默认值,没写就相当于写了mode="scaleToFill"

现在我们改成mode="aspectFit"

image.png

可以看到图片显示在了中间,左右有空白,因为图片进行等比缩小了,使得长的一边也能完全显示。

现在来看下mode="aspectFill"

<view>
    <image class="img" mode="aspectFill"  src="/assets/img/fenjing.webp"></image>
</view>

image.png

可以看到图片被填满了,因为添加了mode="aspectFill" 后,图片会等比缩放使得较短的一边填满image 标签。

来看下 widthFix

<view>
    <image class="img" mode="widthFix"  src="/assets/img/fenjing.webp"></image>
</view>

image.png 可以看到,image 的默认宽度没有变,但是高度变化了,按照图片的比例进行了缩放

来看下heightFix

<view>
    <image class="img" mode="heightFix"  src="/assets/img/fenjing.webp"></image>
</view>

image.png

可以看到,image 默认高度没有变化, 宽度按照图片的比例进行缩放了。

这里只介绍常用的,更多的配置可查看官方文档developers.weixin.qq.com/miniprogram…

6. swiper

swiper 是用来快速用开发轮播功能的,它和swiper-item一起使用。先来看下最基础的使用方式:

6.1 基础轮播

index.wxml

<view>
    <swiper class="banner">
        <swiper-item>1</swiper-item>
        <swiper-item>2</swiper-item>
        <swiper-item>3</swiper-item>
    </swiper>
</view>

index.wxss

.banner swiper-item{
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 100rpx;
}
.banner swiper-item:nth-child(1) {
    background: #f00
}
.banner swiper-item:nth-child(2) {
    background: #333;
}
.banner swiper-item:nth-child(3) {
    background: rgb(71, 209, 52)
}

基础版的默认不会自动轮播,需要手动滑动。且不是循环的,到最后一个就不能继续往下了,只能重新返回,运行效果如下:

swiper-jichu.gif

6.2 自动轮播和循环播放

一般我们做轮播的时候都是要自动轮播的,且大部分情况下都是循环播放,添加这两个功能非常简单,只需要添加autoplay="{{ true }}" 配置和circular="{{ true }}" 配置即可

<view>
    <swiper 
        class="banner"
        autoplay="{{ true }}"
        circular="{{ true }}"
    >
        <swiper-item>1</swiper-item>
        <swiper-item>2</swiper-item>
        <swiper-item>3</swiper-item>
    </swiper>
</view>

运行效果:

swiper-auto.gif

6.3 添加指示器

一般常见的轮播除了能自动轮播和循环播放以外,还有指示器,指示器可以很好的观潮到,我们轮播到了第几个。添加指示器也非常简单,只需要添加indicator-dots="{{ true }}" 即可

<view>
    <swiper 
        class="banner"
        autoplay="{{ true }}"
        circular="{{ true }}"
        indicator-dots="{{ true }}"
    >
        <swiper-item>1</swiper-item>
        <swiper-item>2</swiper-item>
        <swiper-item>3</swiper-item>
    </swiper>
</view>

查看轮播效果:

swiper-dot2.gif

这是swiper 常用的配置,更多配置可查看官方文档:developers.weixin.qq.com/miniprogram…

三、认识小程序的网络请求

1. wx.request

在微信小程序开发中使用 wx.request进行网络请求,在微信小程序中发送网络请求需要注意两个比较重要的点:

  • 请求地址是必须是https 协议的
  • 需要在小程序后台的开发管理 -> 服务器域名 -> request 合法域名,添加上自己需要请求的域名,需要注意官方限制了每个月只能修改5次,所以修改时一定要慎重。

下面看一个基础的使用方式:

// index.js

Page({
    data: {
    },
    getList () {
        wx.request({
            url: 'https://jsonplaceholder.typicode.com/todos',
            success (res) {
                console.log(res)
            }
        })
    },
    onLoad() {
        this.getList()
    }
})

请求回来的数据格式如下:

image.png

小程序默认是get 请求方式,如果想使用其他请求方式可以通过methods属性进行修改。 使用方式如下:

wx.request({
            methods: 'GET',
            url: 'https://jsonplaceholder.typicode.com/todos',
            success (res) {
                console.log(res)
            }
        })

微信小程序支持8种请求方式:

image.png

微信小程序使用 header 属性配置请求头,通过data 属性配置参数,通过timeout 配置超时时间。 具体使用方式如下:

// index.js

Page({
    data: {
    },
    getList () {
        wx.request({
            timeout: 60000,
            header: {
                "Content-Type": "application/json"
            },
            data: {
                postId: 1
            },
            methods: 'GET',
            url: 'https://jsonplaceholder.typicode.com/comments',
            success (res) {
                console.log(res)
            }
        })
    },
    onLoad() {
        this.getList()
    }
})

请求结果:

image.png

2. miniprogram-api-promise

微信小程序官方提供wx.request 使用回调函数的方式来处理请求响应逻辑的, 这在一些情况下容易造成回调地狱, 我们可以使用第三方库来实现promise 的方式来处理。当然你也可以对wx.request 进行二次封装来实现,这里我们就使用第三方库来实现,使用miniprogram-api-promise 来进行实现。

安装 miniprogram-api-promise

npm i miniprogram-api-promise -S

在微信小程序里面只是安装了包是还不能使用的,还需要构建npm 才能使用, 微信开发者工具,点击 工具 -> 构建npm

image.png

在app.js 中加入以下代码,就可以在整个小程序中使用primise 的方式处理响应请求了。

import { promisifyAll } from  'miniprogram-api-promise'

const wxp = wx.p = {}


promisifyAll(wx, wxp)

修改index.js 中使用promise 的方式处理请求:

// index.js
Page({
    data: {
    },
    getList () {
        wx.p.request({
            url: 'https://jsonplaceholder.typicode.com/comments',
            timeout: 60000,
            header: {
                "Content-Type": "application/json"
            },
            data: {
                postId: 1
            },
            methods: 'GET'
        }).then(res => {
            console.log(res)
        }).catch(err => {
            console.log(err)
        })
        
    },
    onLoad() {
        console.log('onLoad')
        this.getList()
    }
})

既然是promise 了,那当然也可以使用async 和await了

// index.js
Page({
    data: {
    },
    async getList () {
        const res = await wx.p.request({
            url: 'https://jsonplaceholder.typicode.com/comments',
            timeout: 60000,
            header: {
                "Content-Type": "application/json"
            },
            data: {
                postId: 1
            },
            methods: 'GET'
        })
        console.log(res)
        
    },
    onLoad() {
        console.log('onLoad')
        this.getList()
    }
})

本篇还会继续更新,若您对小程序开发感兴趣,可以关注后续的更新