# 14.6:!!双向绑定
!! 双向绑定语法是一个语法糖,方便开发者实现父子组件的双向数据同步,本节笔者简单介绍一下 !! 语法糖的使用。
# 14.6.1:约束与限制
!! 双向绑定语法不支持多层父子组件传递。
使用 !! 语法,子组件的 @Event 方法名声明为【$ + @Param属性名】的形式。
@ComponentV2 struct Children { @Param text: paramType = paramValue @Event $text: (value: paramType) => void = (value: paramType) => {} }
1
2
3
4📢:子组件
Children
的text
属性若支持 !! 双向绑定语法,则 @Event 方法名必须是 $text 的形式。
# 14.6.2:简单使用
!! 双向绑定语法的简单使用如下所示:
@Entry @ComponentV2 struct Index {
@Local bookName: string = '《ArkUI实战》'; // 状态属性
build() {
Column({space: 10}) {
Text(this.bookName)
.fontSize(20)
.onClick(() => {
this.bookName = new Date().toISOString()
})
.backgroundColor("#aabbcc")
Children({
text: this.bookName!! // !!语法,双向绑定,会出发父组件更新
})
Children({
text: this.bookName // 单项绑定,不会出发父组件更新
})
}
.width("100%")
.height("100%")
}
}
@ComponentV2 struct Children {
@Param text: string = "children"
@Event $text: (value: string) => void = (value: string) => {}
build() {
Text(this.text)
.fontSize(20)
.fontColor(Color.Pink)
.onClick(() => {
this.$text(new Date().toISOString()) // 回调$text()方法,
})
.backgroundColor("#bbaacc")
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
样例中自定义了 Children
组件,其内部添加了状态属性 text
并同时声明了对应的双向绑定方法 $text(),当点击 Text
组件时会回调该方法。在父组件 Index
内使用 Children
时,第一个使用了双向绑定语法 !!,子组件的属性更改会同步到父组件中;第二个使用的是单项的绑定,子组件的属性更改不会同步到父组件中。
样例运行结果如下所示:

# 14.6.3:和@Event的区别
!! 是双向绑定语法,它和 @Event 的区别是省略了在父组件内传递回调函数的过程,两者都可以实现双向的数据同步,简单样例如下所示:
@Entry @ComponentV2 struct Index {
@Local bookName: string = '《ArkUI实战》';
build() {
Column({space: 10}) {
Text(this.bookName)
.fontSize(20)
.onClick(() => {
this.bookName = new Date().toISOString()
})
.backgroundColor("#aabbcc")
Children({
text: this.bookName!! // 使用双向语法糖!!实现双向的数据同步
})
Children({
text: this.bookName,
$text: (value: string) => { // 使用回调函数形式实现双向的数据同步
this.bookName = value
}
})
}
.width("100%")
.height("100%")
}
}
@ComponentV2 struct Children {
@Param text: string = "children"
@Event $text: (value: string) => void = (value: string) => {}
build() {
Text(this.text)
.fontSize(20)
.fontColor(Color.Pink)
.onClick(() => {
this.$text(new Date().toISOString())
})
.backgroundColor("#bbaacc")
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
样例中第一个 Children
使用了 !! 语法糖实现双向的数据绑定,第二个 Children
组件使用了回调方法的形式并在方法内更改父组件的状态值达到双向的数据绑定。
样例运行结果如下所示:


请作者喝杯咖啡
©arkui.club版权所有,禁止私自转发、克隆网站。