小程序学习

一、小程序

1. 轮播图

swiper组件

indicator-dots 导航器

autoplay 是否自动播放

interval 播放间隔

duration 动画时长

image标签

mode:

  1. scaleToFill (默认值 不保持纵横比缩放图片,使图片的宽高完全拉伸至填满 image 元素。
  2. aspectFit 保持纵横比缩放图片,使图片的长边能完全显示出来。也就是说,可以完整地将图片显示出来。
    意思就是说,将图片缩放到刚好能居中放入 image 中,此时 image 可以有空白部分。
  3. aspectFill 保持纵横比缩放图片,只保证图片的短边能完全显示出来。也就是说,图片通常只在水平或垂直方向是完整的,另一个方向将会发生截取。
  4. widthwise宽度不变,高度自动变化,保持原图宽高比不变。
    意思就是以 image 的宽为准,将原图按比例缩放至正好能放入 image 中,此时image 的高度就是缩放后的图片高度,也就是说 image 不会有多余空白部分。

2.数据绑定

  • 自定义组件事件数据传递

    • //传递方
      this.triggerEvent('eventName', Object)
    • //接收方
      //wxml绑定事件
      <x bind:eventName="OnEvent"/>
      //js实现OnEvent
      OnEvent:function(event){
          this.detail
      }
  • wxml数据传递

    • <x data-valueName="{{value}}" bind:eventName="OnEvent"/>
    • OnEvent:function(event){
          event.target.dataset.valueName
      }
  • 云函数

    • ...then((res)=>{res.data})

      3.用户信息

      3.1检查用户是否授权

      // 检查设置
      wx.getSetting({
      success: (res)=>{
          if(res.authSetting['scope.userInfo']){
              ;
          }
      }
      })

      3.2进行授权

      //wxml
      <button opentype="...." on..../>
      //js
      //完成回调函数

      4.获取用户信息

      4.1获取信息

      4.1.1 <open-data>

      4.1.2 wx.getUserInfo

      4.1.3 button

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

      4.2获取openId

      4.2.1 传统微信登录-

      ​ wx.login获取code,wx.request将code传输给后端服务器,后端服务器使用code换取openid和session_key

      4.2.2 云开发

      5.API

      API调试需要使用真机进行

      5.1 发送订阅消息(模板信息已下线)

      5.1.1 获取订阅ID

      [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-emXMWBG9-1612419241354)(C:\Users\litan\AppData\Roaming\Typora\typora-user-images\image-20200615091223687.png)]

      5.1.2 获取下发权限

      wx.requestSubscribeMessage(Object object)

      wx.requestSubscribeMessage({
      tmplIds: [''],
      success (res) { }
    
    #### 5.1.3 发送订阅消息
    
    `subscribeMessage.send`
    
    > 本接口应在服务器端调用
    
    ## # Tips
    
    ### 1. 下拉刷新
  • 在json文件中添加enablePullDownRefreshtrue
  • 在js文件添加onPullDownRefresh函数
  • 调用 wx.stopPullDownRefresh()停止刷新动画

    2. 页面json文件

  • 在页面 json文件中添加 navagationBarTitleText 字段完成配置navigationBar
  • disableScoll 上下是否可以拖动

    3. 样式不生效

    把全局配置文件app.json中的 “style”: "v2“ 删除即可。

    4. 节点绑定事件

  • bind: 事件冒泡
  • catch:事件不冒泡

    5. 页面

    getCurrentPages(): 页面栈

    二、组件化开发

    1. 概念和意义

    面向用户独立可复用的交互元素的封装。

    组件=结构+逻辑+样式

    意义:代码组合、优化项目资源管理、有利于单元测试、重构友好

    2. 设计原则

  • 高内聚:组件内部
  • 低耦合:组件间独立
  • 单一职责:单一功能
  • 避免过多参数

    3.组件

    3.1 使用步骤

  • 创建组件
  • 修改在需要组件的页面的json文件
  • 在wxml中使用定义的组件

    3.2 组件内容

    properties

    定义传递过来的数据

    properties:{
      type: String/Object
      value: ''/{}
    }

    data

    组件内部数据

    methods

    组件方法

    数据监听器

    observers:{
      '属性': fuction(属性变量){函数体}
    }

    3.3 组件样式隔离

    组件样式隔离使得组件无法使用外部样式

    处理方法:

  • 在组件文件中引入所需要的样式
  • 调用时传入样式
  • 传递属性 <componet classnameOne="classname1" classnameTwo="classname2"/>
  • 配置组件externalClasser 属性

    externalClasses:['classnameOne','classnameTwo']

  • 在组件中使用classnameOneclassnameTwo样式
  • 注意:传递进来的样式在组件中不能进行修改
  • 配置 options:{styleIsolation: ''}

    • isolated 表示启用样式隔离,在自定义组件内外,使用 class 指定的样式将不会相互影响(一般情况下的默认值);
    • apply-shared 表示页面 wxss 样式将影响到自定义组件,但自定义组件 wxss 中指定的样式不会影响页面;
    • shared 表示页面 wxss 样式将影响到自定义组件,自定义组件 wxss 中指定的样式也会影响页面和其他设置了 apply-sharedshared 的自定义组件。(这个选项在插件中不可用。)

    4.插槽 slot

  • 启用多个插槽 option{multipleSlots:true}
  • 设置插槽 name属性
  • 通过设置viewslot属性进行绑定

    三、云开发

    1. 使用三方包

  • 安装

    npm install request-promise

  • 导入

    const rp = require('request-promise')

    2. 云数据库

    2.1使用步骤

  • 获取云数据库实例cloud.database()
  • 根据实例获取集合db.collections('name')
  • 操作数据

    2.2模糊搜索

    使用数据库的正则api

    w = {
      itemName: db.RegExp({
      regexp: keyword,
      options: 'i'
      })
    }
    // 将作为参数进行where查询

    注意

  • 数据库每次请求数据有限制
  • 先创建集合,再操作数据

    3.云存储

    3.1存文件

    wx.cloud.uploadFile({
      cloudPath: `blog/${Date.now()}-${Math.random()*10000000}${suffix}`, // 云存储地址
      filePath: item, // 本地地址
      success: (res) => {  // 成功回调函数
          fileIDlist.push(res.fileID) // res.fileID 可以用来取文件
      },
      fail: (err) => {  // 失败回调函数
          console.log(err)
      }
    })

    3.2取文件

  • 图片类型可以直接将fileID作为image.src
  • wx.cloud.downloadFile

    4.云函数

    4.1 入口

    入口 exports.main = async(event, context) => {}

    4.2 定时触发器

    //config.json
    {
      "triggers":[
      {
          "name"://名称,
          "type":,//
          "config"://秒 分钟 小时 日 月 星期 年,
      }
      ]
    }

    4.3 路由优化

    使用tcb-router相似云函数在一个函数中进行处理

    4.4 小程序端调用云函数

    wx.callFuntion({
      name: 'functionName',
      data: {
          ...
      }
    }).then((res)=>{})
    .catch((err)=>{})

// 云函数接收参数: event.itemName


## 四、npm包

### 1. request-promise

const playlist = await rp(URL).then((res) => {
return JSON.parse(res).result
})
// 创建一个rp获取URL的资源,并将结果解析返回给playlist


### 2. tcb-router

一个koa风格的云函数路由库

// 云函数的 index.js
const TcbRouter = require('./router');

exports.main = (event, context) => {

const app = new TcbRouter({ event });

// app.use 表示该中间件会适用于所有的路由
app.use(async (ctx, next) => {
    ctx.data = {};
    await next(); // 执行下一中间件
});

// 路由为数组表示,该中间件适用于 user 和 timer 两个路由
app.router(['user', 'timer'], async (ctx, next) => {
    ctx.data.company = 'Tencent';
    await next(); // 执行下一中间件
});

// 路由为字符串,该中间件只适用于 timer 路由
app.router('timer', async (ctx, next) => {
    ctx.data.name = 'flytam';
    await next(); // 执行下一中间件
}, async (ctx, next) => {
    ctx.data.sex = await new Promise(resolve => {
    // 等待500ms,再执行下一中间件
    setTimeout(() => {
        resolve('male');
    }, 500);
    });
    await next(); // 执行下一中间件
}, async (ctx)=>  {
    ctx.data.city = 'Taishan';
    // ctx.body 返回数据到小程序端
    ctx.body = { code: 0, data: ctx.data };
});

return app.serve();

}

// 调用名为 router 的云函数,路由名为 user
wx.cloud.callFunction({

// 要调用的云函数名称
name: "router",
// 传递给云函数的参数
data: {
    $url: "user", // 要调用的路由的路径,传入准确路径或者通配符*
    other: "xxx"
}

});


## 五、EcmaScript

### 1. 异步

#### 1.1 Promise

new Promise((resolve,reject)=>{

//pending
resolve() // 变为fulfilled状态
rejected() // 变为regected状态

}).then((res)=>{}) //fulfilled 调用
.catch((res)=>{}) // rejected 调用

Promise.all([promises]).then().catch() //全部为fulfilled进入then,否则进入catch
// 多个请求并发

Promise.race([promises]).then().catch() //有一个完成了就进入then,都失败了进入catch
// 判断请求超时


#### 1.2 async await

async定义函数,函数为Promise对象

await 等待异步操作执行完成

### 常用函数

#### concat

数组追加

#### trim

去除字符空格

---
转载至CSDN博主:[[李唐敏民](https://blog.csdn.net/qq_39041210 "李唐敏民")]
---
最后修改:2021 年 02 月 18 日
如果觉得我的文章对你有用,请随意赞赏