


A brief analysis of several ways of communicating between slots and parent-child components in mini programs
This article will introduce to you the slots in the WeChat applet and several methods of parent-child component communication. I hope it will be helpful to you!
Today we will take a look at the communication between slots and parent-child components in the mini program, and see what the differences are with vue? [Related learning recommendations: 小program development tutorial]
1. Slot
1. What is a slot ?
In the wxml
structure of a custom component, a node (slot) can be provided to host the wxml## provided by the component user. # Structure
the sub-component digging the hole and the parent component filling the hole . When the parent component uses the child component, it determines some layout display inside the child component
- The child component fills the hole by digging holes
- The parent component fills the hole through the content in the middle of the component tag
2. Single slot
In the applet, by default only one is allowed in each custom componentslot Placeholder, this limit on the number is called a single slot
- By default, there can only be one
- in a component's
wxml
slot When you need to use multiple - slot
, you can declare the enablement
in the component
js - Note: small Currently, there are only default slots and multiple slots in the program. Scope slots are not supported at the moment.
<!-- 组件的封装者 --> <view class="wrapper"> <view>这里是组件的内部节点</view> <!-- 对于不确定的内容,可以使用<slot>进行占位,具体的内容由组件的使用者决定 --> <slot></slot> </view> <!-- 组件的使用者 --> <component-tag-name> <!-- 这部分内容将被放置在组件<slot>的位置上 --> <view>这里是插入到组件slot的内容</view> </component-tag-name>
3. Start multiple slots
In the custom component of the applet, when you need to use multiple slots, you can in the .js
file of the component
Component({ options: { multipleSlots: true // 在组件定义时的选项中启用多 slot 支持 }, properties: { /* ... */ }, methods: { /* ... */ } })
4. Define multiple slots
Can be in the component's.wxml Use multiple tags in to distinguish different slots with different
name
<!-- 组件模板 --> <view class="wrapper"> <!-- name 为 before 的第一个 slot 插槽 --> <slot name="before"></slot> <view>这是一段固定的文本内容</view> <!-- name 为 after 的第二个 slot 插槽 --> <slot name="after"></slot> </view>
2. Father and son Component communication
1. Parent-child component communication
- Property binding
Used for parent components to set data to specified properties of child components. Only
JSON
compatible data can be set (only data can be passed, methods cannot be passed)
- Event binding Certainly Used for child components to pass data to parent components. You can pass any data (including arrays and methods)
- Get the component instance
The parent component can also obtain the child component instance object through
this.selectComponent()
so that it can directly access any data and methods of the child component
2. Attribute binding
- #Transfer data
Property binding is used to transfer values from parent to child, and can only pass common types of data. Methods cannot be passed to child components.
// 父组件的 data 节点 data: { count: 0 } // 父组件的wxml 结构 <my-test3 count="{{count}}"></my-test3> <view>~~</view> <view>父组件中,count值为:{{count}}</view>
- Accept data
// 子组件的 properties 节点 properties: { count: Number } // 子组件的 wxml 结构 <text>子组件中,count值为:{{count}}</text>
3. The core implementation steps of event binding
Event binding is used to realize the transmission from child to parent Value, any type of data can be passed. The usage steps are as follows:- In
- js
of
parent component, define a function, which will be passed to the child component in the form of a custom event
In - wxml
of the
parent component, pass the function reference defined in step 1 to the child component
## in the form of a custom event #In js - of
subcomponent
, by callingthis.triggerEvent('custom event name', {/* parameter object*/})
, Data is sent to the parent componentIn the
js - of the parent component, the data passed by the child component is obtained through
e.detail
4. The core implementation code of event binding
Step 1: In the- js
- of the parent component, define a function , this function will be passed to the child component in the form of a custom event
// 父组件中定义 syncCount 方法 // 将来,这个方法会被传递给子组件,供子组件进行调用 syncCount() { console.log('syncCount') },
- In wxml
- , pass the function reference defined in step 1 to the sub-component in the form of a custom event
<!-- 使用 bind: 自定义事件名称(推荐:结构清晰) --> <my-test3 count="{{count}}" bind:sync="syncCount"></my-test3> <!-- 或在 bind 后面直接协商自定义事件名称 --> <my-test3 count="{{count}}" bindsync="syncCount"></my-test3>
- js
- of
subcomponent
, by callingthis.triggerEvent('custom event name', {/* parameter object*/})
, send data to the parent component The code is as follows (example):
// 子组件的wxml结构 <text>子组件中,count值为:{{count}}</text> <button type="primary" bindtap="addCount">+1</button> // 子组件中的 js 代码 methods: { addCount() { this.setData({ count: this.properties.count + 1 }) this.triggerEvent('sync', {value: this.properties.count}) } }
- 步骤 4:在父组件的
js
中,通过e.detail
获取到子组件传递过来的数据
代码如下(示例):
syncCount(e) { // console.log(e.detail.value) this.setData({ count: e.detail.value }) }
5. 使用 selectComponent 获取组件实例
父组件如何获得子组件实例?
可在父组件里调用 this.selectComponent("id或class选择器")
,获取子组件的实例对象,从而直接访问子组件的任意数据和方法。调用时需要传入一个选择器
,例如 this.selectComponent(".my-component")
代码如下(示例):
// wxml结构 <my-test3 count="{{count}}" bind:sync="syncCount" class="customA" id="cA"></my-test3> <button bindtap="getChild">获取子组件实例</button> getChild() { // 按钮的tap事件处理函数 // 切记下面参数不能传递标签选择器 'my-test3',不然返回的是 null const child = this.selectComponent('.customA') // 也可以传递 id 选择器 #cA child.setData({ count: child.properties.count + 1 }) // 调用子组件的 setData 方法 child.addCount() // 调用子组件的 addCount 方法 }
更多编程相关知识,请访问:编程入门!!
The above is the detailed content of A brief analysis of several ways of communicating between slots and parent-child components in mini programs. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

This article provides a detailed guide to safe download of Ouyi OKX App in China. Due to restrictions on domestic app stores, users are advised to download the App through the official website of Ouyi OKX, or use the QR code provided by the official website to scan and download. During the download process, be sure to verify the official website address, check the application permissions, perform a security scan after installation, and enable two-factor verification. During use, please abide by local laws and regulations, use a safe network environment, protect account security, be vigilant against fraud, and invest rationally. This article is for reference only and does not constitute investment advice. Digital asset transactions are at your own risk.

H5 is more flexible and customizable, but requires skilled technology; mini programs are quick to get started and easy to maintain, but are limited by the WeChat framework.

Compatibility issues and troubleshooting methods for company security software and application. Many companies will install security software in order to ensure intranet security. However, security software sometimes...

Discussion on the JS resource caching issue of Enterprise WeChat. When upgrading project functions, some users often encounter situations where they fail to successfully upgrade, especially in the enterprise...

The choice of H5 and applet depends on the requirements. For applications with cross-platform, rapid development and high scalability, choose H5; for applications with native experience, rich functions and platform dependencies, choose applets.

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

This article provides a brief guide to buying and selling of Binance virtual currency updated in 2025, and explains in detail the operation steps of virtual currency transactions on the Binance platform. The guide covers fiat currency purchase USDT, currency transaction purchase of other currencies (such as BTC), and selling operations, including market trading and limit trading. In addition, the guide also specifically reminds key risks such as payment security and network selection for fiat currency transactions, helping users to conduct Binance transactions safely and efficiently. Through this article, you can quickly master the skills of buying and selling virtual currencies on the Binance platform and reduce transaction risks.
