Summary of strengthening the basics of WeChat mini programs

WBOY
Release: 2022-10-13 14:11:20
forward
2693 people have browsed it

This article brings you related issues aboutWeChat Mini Program, which mainly introduces some basic content, including custom components, style isolation, data, methods and properties, etc. , let’s take a look at it, I hope it will be helpful to everyone.

Summary of strengthening the basics of WeChat mini programs

【Related learning recommendations:小program learning tutorial

1. Custom components

1.1. Create components

  • In the root directory of the project, right-click and create components -> test folder

  • On the newly created components -> test folder, right-click the mouse and click New Component

  • Type the name of the component and press Enter, the 4 corresponding to the component will be automatically generated files, the suffixes are .js, .json, .wxml and .wxss

1.2, reference components

  • Local reference: The component can only be used within the currently referenced page

  • Global reference: The component can be used in each mini program page

1.3. Local reference components

The way to reference components in the .json configuration file of the page is called local reference. The sample code is as follows:

# 在页面的 .json 文件中,引入组件 { "usingComponents": { "my-test": "/components/test/test" } } # 在页面的 .wxml 文件中,使用组件 
Copy after login

1.4. Global reference components

The way to reference components in the app.json global configuration file is called global reference . The sample code is as follows:

# 在 app.json 文件中,引入组件 { "usingComponents": { "my-test": "/components/test/test" } }
Copy after login

1.5. Global reference VS local reference

Choose the appropriate reference method based on the frequency and scope of use of the component. :

  • If a component is frequently used in multiple pages, it is recommended to make a global reference

  • Use a component only on a specific page is used in, it is recommended to make a local reference

1.6. The difference between components and pages

From the surface , components and pages are composed of four files: .js, .json, .wxml and .wxss. However, there are obvious differences between the .js and .json files of components and pages:

  • The "component": true attribute needs to be declared in the .json file of the component

  • The Component() function is called in the .js file of the component

  • The event processing function of the component needs to be defined in the methods node

2. Style isolation

##2.1. Component style isolation

By default, custom components The style only takes effect on the current component and will not affect the UI structure outside the component.

Prevent external styles from affecting the internal styles of components

Prevent component styles from destroying external styles

2.2. Notes on component style isolation

The global styles in app.wxss are not valid for components

Only the class selector will have the style isolation effect, and the id selector, attribute selector, and label selector will not be affected. Impact of style isolation

It is recommended to use class selectors in components and pages that reference components. Do not use id, attribute, and label selectors

2.3. Modify the style of the component Isolation options

By default, the style isolation feature of custom components can prevent the interference between internal and external styles of the component. But sometimes, we want to be able to control the style inside the component from the outside. At this time, you can modify the style isolation option of the component through stylelsolation. The usage is as follows:

# 在组件的 .js 文件中新增如下配置 Component({ options: { stylelsolation: 'isolated' } }) # 或在组件的 .json 文件中新增如下配置 { "stylelsolation": "isolated" }
Copy after login

2.4. Optional values of stylelsolation

| Selected value | Default value | Description |

| :----------: | :----: | --------------- -------------------------------------------------- -------------------------------------------------- ---------- | --------------------------------------- ---------------------------------- |

| isolated | 是 | 表示启用样式隔离 | 表示启用样式隔离,在自定义组件内外,使用 class 指定的样式将不会互相影响 |

| apply-shared | 否 | 表示页面 wxss 样式将影响到自定义组件,但自定义组件 wxss 中指定的样式不会影响页面 |

| shared | 否 | 表示页面 wxss 样式将影响到自定义组件,自定义组件 wxss 中指定的样式也会影响页面和其他设置了 apply-shared 或 shared 的自定义组件 |

3、数据、方法和属性

3.1、data 数据

在小程序组件中,用于组件模板渲染和私有数据,需要定义到 data 节点中,示例如下:

Component({  data: { count: 0 } })
Copy after login

3.2、methods 数据

在小程序组件中,事件处理函数和自定义方法需要定义到 methods 节点中,示例代码如下:

Component({  methods: {  addCount() { this.setData({count: this.data.count + 1});  this._showCount() },  _showCount() { wx.showToast({ title: 'count值为:' + this.data.count, icon: 'none' }) } } })
Copy after login

3.3、properties 属性

在小程序组件中,properties 是组件的对外属性,用来接收外界传递到组件中的数据,示例代码如下:

Component({  properties: {  max: { type: Number, value: 10 },  max: Number } })
Copy after login

3.4、data 和 properties 的区别

在小程序的组件中,properties 属性和 data 数据的用法相同,它们都是可读可写的,只不过:

  • data 更倾向于存储组件的私有数据

  • properties 更倾向于存储外界传递到组件中的数据

Component({ methods: { showInfo() {  console.log(this.data === this.properties) } } })
Copy after login

3.5、使用 setData 修改 properties 的值

由于 data 数据和 properties 属性在本质上没有任何区别,因此 properties 属性的值也可以用于页面渲染,或使用 setData 为 properties 中的属性重新赋值,示例代码如下:

# 在组建的 .wxml 文件中使用 properties 属性的值 max属性的值为:{{max}} Component({ properties: { max: Number }, methods: { addCount() { this.setData({ max: this.properties.max + 1 }) } } })
Copy after login

4、数据监听器

4.1、什么是数据监听器

数据监听器用于监听和响应任何属性和数据字段的变化,从而执行特定的操作。它的作用类似于 vue 中的 watch 侦听器。在小程序组件中,数据监听器的基本语法格式如下:

Component({ observers: { '字段A, 字段B': function(字段A的心智, 字段B的新值) { } } })
Copy after login

4.2、数据监听器的基本用法

Component({ data: { n1: 0, n2: 0, sum: 0 }, methods: { addN1() { sthis.setData({ n1: this.data.n1 + 1 })}, addN2() { sthis.setData({ n2: this.data.n2 + 1 })} }, observers: { 'n1, n2': function(n1, n2) { this.setData({sum: n1 + n2}) } } })
Copy after login

4.3、监听对象属性的变化

# 数据监听器支持监听对象中单个或多个属性的变化,示例代码如下: Component({ observers: { '对象.属性A, 对象.属性B': function(属性A的新值, 属性B的心智){} } }) # 监听对象中所有属性的变化 Component({ observers: { 'obj.**': function(obj){} } })
Copy after login

5、纯数据字段

5.1、什么是纯数据字段

纯数据字段指的是那些不用于界面渲染的 data 字段。

应用场景:例如有些情况下,某些 data 中的字段既不会展示在界面上,也不会传递给其他组件,仅仅在当前组件内部使用。带有这种特性的 data 字段适合备设置为储数据字段

好处:纯数据字段有助于提升页面更新的性能

5.2、使用规则

在 Component 构造器的 options 节点中,指定 pureDataPattern 为一个正则表达式,字段名符合这个正则表达式的字段将成为纯数据字段,示例代码如下:

Component({ options: {  pureDataPattern: /^_/ }, data: { a: true, // 普通数据字段 _b: true // 纯数据字段 } })
Copy after login

6、组件的生命周期

6.1、组件的全部生命周期函数

Summary of strengthening the basics of WeChat mini programs

6.2、组件主要的生命周期函数

在小程序组件中,最重要的生命周期函数有 3 个,分别是 created、attached、detached。它们各自的特点如下:

  • 组件实例刚被创建好的时候,created 生命周期函数会被触发

此时还不能调用 setData

通常在这个生命周期函数中,只应该用于给组件的 this 添加一些自定义的属性字段

  • 在组建完全初始化完毕、进入页面节点树后,attached 生命周期函数会被触发

此时,this.data 已被初始化完毕

这个生命周期很有用,绝大多数初始化的工作可以在这个时机进行

  • 组件离开页面节点树后,detached 生命周期函数会被触发

退出一个页面时,会触发页面内每个自定义组件的 detached 生命周期函数

此时适合做一些清理性质的工作

6.3、lifetimes 节点

在小程序组件中,生命周期函数可以直接定义在 Component 构造器的第一级参数中,可以在 lifetimes 字段内进行声明(这是推荐的方式,其优先级最高)。示例代码如下:

Component({  lifetimes: { attached() {}, // 在组件实例进入页面节点树时执行 detached() {}, // 在组件实例被从页面节点树移除时执行 },  attached() {}, // 在组件实例进入页面节点树时执行 detached() {}, // 在组件实例被从页面节点树移除时执行 })
Copy after login

6.4、什么是组件所在页面的生命周期

有时,自定义组件的行为依赖于页面状态的变化,此时就需要用到组件所在页面的生命周期

Summary of strengthening the basics of WeChat mini programs

6.5、pageLifetimes 节点

# 组件所在页面的生命周期函数,需要定义在 pageLifetimes 节点中 Component({ pageLifetimes: { show: function() {}, // 页面被展示 hide: function() {}, // 页面被隐藏 resize: function(size) {} // 页面尺寸变化 } })
Copy after login

7、插槽

7.1、什么是插槽

在自定义组件的 wxml 结构中,可以提供一个 slot 节点(插槽),用于承载组件使用者提供的 wxml 结构。

7.2、单个插槽

在小程序中,默认每个自定义组件中只允许使用一个 slot 进行占位,这种个数上限制叫做单个插槽

  这里是组件的内部节点      这里是插入到组件slot中的内容 
Copy after login

7.3、启用多个插槽

在小程序的自定义组件中,需要使用多个 slot 插槽是,可以在组件的 .js 文件中,通过如下方式进行启用,示例代码如下:

Component({ options: { multipleSlots: true // 在组件定义时,启用多个 slot 支持 } })
Copy after login

7.4、定义多个插槽

可以在组件的 .wxml 中使用多个 slot 标签,以不同的 name 来区分不同的插槽。示例代码如下:

    这是一段固定的文本内容   
Copy after login

7.5、使用多个插槽

在使用带有多个插槽的自定义组件时,需要用 slot 属性来将节点插入到不同的 slot 中。示例代码如下:

   这里是插入到组件 slot name="before"中的内容  这里是插入到组件 slot name="after"中的内容 
Copy after login

8、父子组件之间的通信

8.1、父子组件之间的通信的 3 种方式

属性绑定

用于父组件向子组件的指定属性设置数据,仅能设置 JSON 兼容的数据

事件绑定

用于子组件向父组件传递数据,可以传递任意数据

获取组件实例

父组件还可以通过 this.selectComponent() 获取子组件实例对象

这样旧可以直接访问子组件的任意数据和方法

8.2、属性绑定

属性绑定用于实现父向子传值,而且只能传递普通类型的数据,无法将方法传递给子组件。父组件的示例代码如下:

 data: { count: 0 }  
Copy after login
 properties: { count: Number }  子组件种,count值为:{{count}}
Copy after login

8.3、事件绑定

事件绑定用于实现子向父传值,可以传递任何类型的数据。使用步骤如下:

在父组件的 js 中,定义一个函数,这个函数即将通过自定义事件的形式,传递给子组件

 syncCount() { console.log('syncCount') }
Copy after login

在父组件的 wxml 中,通过自定义事件的形式,将步骤 1 中定义的函数引用,传递给子组件

   
Copy after login

在子组件的 js 中,通过调用 this.triggerEvent('自定义事件名称',{参数对象}),将数据发送到父组件

 子组件中,count:{{count}}  # 子组件的 js 代码 methods: { addCount() { this.setData({ count: this.properties.count + 1 }) this.triggerEvent('sync', { value: this.properties.count }) } }
Copy after login

在父组件的 js 中,通过 e.detail 获取到子组件传递过来的数据

syncCount(e) { this.setData({ count: e.detail.value }) }
Copy after login

8.4、获取组件实例

可在父组件里调用 this.selectComponent('id 或 class 选择器'),获取子组件的实例对象,从而直接访问子组件的任意数据和方法。

   getChild() {  const child = this.selectComponent('.test')  child.setData({ count: child.properties.count + 1 })  child.addCount() }
Copy after login

9、behaviors

9.1、什么是 behaviors

behaviors 是小程序中,用于实现组件间代码共享的特性,类似于 Vue.js 中的 mixins

9.2、behaviors 的工作方式

每个 behavior 可以包含一组属性、数据、生命周期函数和方法。组件引用它时,它的属性、属性和方法会被合并到组件中。

每个组件可以引用多个 behavior,behavior 也可以引用其它 behavior

9.3、创建 behavior

调用 Behavior(Object object) 方法即可创建一个共享的 behavior 实例对象,供所有的组件使用

# 调用 Behavior() 方法,创建实例对象 # 并使用 module.exports 将 behavior 实例对象共享出去 module.exports = Behavior({ # 属性节点 properties: {}, # 私有数据节点 data: {}, # 事件处理函数和自定义方法节点 methods: {} })
Copy after login

9.4、导入并使用 behavior

在组件中,使用 require() 方法导入需要的 behavior,挂载后即可访问 behavior 中的数据或方法,示例代码如下:

# 使用 require() 导入需要自定义 behavior 模块 const myBehavior = require('my-behavior') Component({  behaviors: [myBehavior] })
Copy after login

9.5、behavior 中所有可用的节点

Summary of strengthening the basics of WeChat mini programs

10、使用 npm 包

10.1、小程序对 npm 的支持与限制

目前,小程序已经支持使用 npm 安装第三方包,从而来提高小程序的开发效率。但是,在小程序中使用 npm 包有如下 3 个限制:

  • 不支持依赖于 Node.js 内置库的包

  • 不支持依赖于浏览器内置对象的包

  • 不支持依赖于 C++ 插件的包

10.2、API Promise 化

  • 基于回调函数的异步 API 的缺点

默认情况下,小程序官方提供的异步 API 都是基于回调函数实现的,例如,网络请求的 API 需要按照如下的方式调用:

wx.request({ method: '', url: '', data: {}, success: () => {} })
Copy after login

缺点:容易造成回调地狱的问题,代码的可读性、维护性差

  • 什么是 API Promise 化

API Promise 化,指定是通过额外的配置,将官方提供的、基于回调函数的异步 API,升级改造为基于 Promise 的异步 API,从而提高代码的可读性、维护性、避免回调地狱的问题

  • 实现 API Promise 化

在小程序中,实现 API Promise 化主要依赖于 minprogram-api-promise 这个第三方的 npm 包。它的安装和使用步骤如下:

npm install --save minprogram-api-promise # 在小程序入口文件中(app.js),只需要调用一次 promisifyAll() 方法 import { promisifyAll } from 'minprogram-api-promise' const wxp = wx.p = {} promisifyAll(wx, wxp)
Copy after login
  • 调用 Promise 化之后的异步 API

# 页面的 .wxml 结构  # 在页面的 .js 文件中,定义对应的 tap 事件处理函数 async getInfo() { const { data: res } = await wx.p.request({ method: 'GET', url: '', data: {} }) }
Copy after login

11、全局数据共享

11.1、什么是全局数据共享

全局数据共享(又叫做:状态管理)是为了解决组件之间数据共享的问题

开发中常用的数据共享方案有:Vuex、Redux、MobX 等

11.2、小程序中的全局数据共享方案

在小程序中,可使用 mobx-miniprogram 配合 mobx-miniprogram-bindings 实现全局数据共享。其中:

  • mobx-miniprogram 用来创建 Store 实例对象

  • mobx-miniprogram-bindings 用来把 Store 中的共享数据或方法,绑定到组件或页面中使用

安装 MobX 相关的包

# 在项目运行如下的命令,安装MobX相关的包 npm install --save mobx-miniprogram mobx-miniprogram-bindings
Copy after login

注意:MobX 相关的包安装完毕之后,记得删除 miniprogram_npm 目录后,重新构建 npm

创建 MobX 的 Store 实例

import { observable, action } from 'mobx-miniprogram' export const store = observable({ // 数据字段 numA: 1, numB: 2, //计算属性 get sum() { return this.numA + this.numB }, // actions 方法,用来修改 store 中的数据 updateNumA: action(function(step) { this.numA += step }), updateNumB: action(function(step) { this.numB += step }), })
Copy after login

将 Store 中的成员绑定到页面中

# 页面的 .js 文件 import { createStoreBindings } from 'mobx-miniprogram-bindings' import { store } from './store' Page({ onLoad() { this.storeBindings = createStoreBindings(this, { store, fields: ['numA', 'numB', 'sum'], actions: ['updateNumA'] }) },  onUnload() { this.storeBindings.destroyBindings() } })
Copy after login

在页面上使用 Store 中的成员

# 页面的 .wxml {{numA}} + {{numB}} = {{sum}} numA + 1 numA - 1  btnHandler(e) { this.updateNumA(e.target.dataset.step) }
Copy after login

将 Store 中的成员绑定到组件中

import { storeBindingsBehavior } from 'mobx-miniprogram-bindings' import { store } from './store' Component({ behaviors: [storeBindingsBehavior], storeBindings: { store, fields: { numA: () => store.numA, numB: (store) => store.numB, sum: 'sum' }, actions: { updateNumA: 'updateNumA' } } })
Copy after login

在组件中使用 Store 中的成员

# 组件的 .wxml 结构 {{numA}} + {{numB}} = {{sum}} numA + 1 numA - 1  btnHandler(e) { this.updateNumA(e.target.dataset.step) }
Copy after login

【相关学习推荐:小程序学习教程

The above is the detailed content of Summary of strengthening the basics of WeChat mini programs. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.im
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!